简体   繁体   中英

How to get a spring bean in a bean-defining method

I have a java config where ServiceB depends on ServiceA:

@Bean
ServiceA getServiceA() { return new ServiceA(); }
@Bean
ServiceB getServiceB() { return new ServiceB(getServiceA()); }

Then I want to declare ServiceA (but no ServiceB) as a component. I add @ScanPackage to config and annotate ServiceA:

@Component
class ServiceA { .. }

How to declare method getServiceB() now?

Spring auto-injects method parameters by type for Bean defining methods:

@Bean
ServiceB getServiceB(ServiceA serviceA) {
    return new ServiceB(serviceA);
}

Now you don't have to worry about how ServiceA is provided.

As Rohan already wrote in his answer , Spring's @Bean annotation can inject dependencies of other Spring beans, in the same manner as constructor-based dependency injection does.

I would just add that there are also other possibilities to do dependency injection, when defining a bean in java config. @Configuration annotated class is a Spring bean as any other Spring bean, so you can auto-wire a dependency, as is usually done in Spring and then use this dependency when defining your @Bean , like:

@Autowired
private ServiceA serviceA;

@Bean
public ServiceB getServiceB() {
    return new ServiceB(serviceA);
}

Since Spring Framework 4.3, you are also able to do constructor injection in @Configuration classes - which is yet another way to inject dependencies.

See more details in spring documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM