[英]How to get a spring bean in a bean-defining method
I have a java config where ServiceB depends on ServiceA: 我有一个Java配置,其中ServiceB取决于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. 然后,我想将ServiceA(但没有ServiceB)声明为组件。 I add @ScanPackage
to config and annotate ServiceA: 我将@ScanPackage
添加到配置并注释ServiceA:
@Component
class ServiceA { .. }
How to declare method getServiceB()
now? 现在如何声明方法getServiceB()
?
Spring auto-injects method parameters by type for Bean defining methods: Spring为Bean定义方法按类型自动注入方法参数:
@Bean
ServiceB getServiceB(ServiceA serviceA) {
return new ServiceB(serviceA);
}
Now you don't have to worry about how ServiceA
is provided. 现在,您不必担心如何提供ServiceA
。
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. 正如Rohan在他的答案中所写,Spring的@Bean
注释可以注入其他Spring bean的依赖项,就像基于构造函数的依赖项注入一样。
I would just add that there are also other possibilities to do dependency injection, when defining a bean in java config. 我只想补充一点,在java config中定义bean时,还有其他可能性可以进行依赖注入。 @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: 与其他任何Spring bean一样, @Configuration
注释的类是Spring bean,因此您可以像通常在Spring中那样自动@Bean
依赖项,然后在定义@Bean
时使用此依赖@Bean
,例如:
@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. 从Spring Framework 4.3开始,您还可以在@Configuration
类中进行构造函数注入-这是注入依赖关系的另一种方法。
See more details in spring documentation . 在spring文档中查看更多细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.