2

I have a @Configuration annotated class, that has @Bean annotated methods. Most of them return simply new instances that have no DI dependencies e.g.:

@Bean
public UserService getUserService() {
    return new InMemoryUserService();
}

But some of the beans need constructor injection, e.g.

@Bean
public BookingService getBookingService() {
    return new InMemoryBookingServiceImpl(???); // i need to inject UserService to constructor
}

How can I do it?

dragonfly
  • 17,407
  • 30
  • 110
  • 219
  • why do you need to create instance of InMemoryBookingServiceImpl explicitly? Can it be annotated as a @Component? – MK. May 25 '16 at 18:31
  • Wouldn't be easier to create the bean by annotating the `InMemoryBookingServiceImpl` class with `@Component` while autowiring the dependencies into it? – tkralik May 25 '16 at 18:32
  • http://stackoverflow.com/questions/24014919/converting-spring-xml-file-to-spring-configuration-class – Sotirios Delimanolis May 25 '16 at 18:55

1 Answers1

3

Just pass the beans you need as a parameter to the method.

@Bean
public UserService getUserService() {
    return new InMemoryUserService();
}

@Bean
public BookingService getBookingService(UserService userServ) {
    return new InMemoryBookingServiceImpl(userServ); 
}

Here when Spring gets to the getBookingService it will see that it requires a bean of type UserService and will look for one in the context.

See the docs

All the dependency injection rules apply. Like if no bean of that type is found an exception is thrown, or if more that one bean of that type is found you have to use @Qualifier to specify a name of the bean that you want, or mark one of the beans with @Primary

Another option is to directly use the the method that produces the dependency bean:

@Bean
public UserService getUserService() {
    return new InMemoryUserService();
}

@Bean
public BookingService getBookingService() {
    return new InMemoryBookingServiceImpl(getUserService()); 
}
Evgeni Dimitrov
  • 21,976
  • 33
  • 120
  • 145
  • 2
    just a comment on the 2nd option (calling the method). Spring has some strong voodoo (bytecode manipulation) where it will still create one instance of `UserService`, even if the method `getUserService()` is called several times. – Augusto May 25 '16 at 21:17