在Spring的Java配置中自动装配bean [英] Autowire a bean within Spring's Java configuration
问题描述
是否可以在用Java编写的Spring配置中使用Spring的 @Autowired
注释?
Is it possible to use Spring's @Autowired
annotation within a Spring configuration written in Java?
例如:
@Configuration
public class SpringConfiguration{
@Autowired
DataSource datasource;
@Bean
public DataSource dataSource(){
return new dataSource();
}
// ...
}
显然,DataSource接口不能直接实例化,但为了简化我直接在这里实例化它。目前,当我尝试上述操作时,数据源对象仍然为空,并且不会由Spring自动装配。
Obviously a DataSource interface cannot be directly instantiated but I directly instantiated it here for simplification. Currently, when I try the above, the datasource object remains null and is not autowired by Spring.
我得到了 @Autowired
通过返回 FactoryBean< SessionFactory>
来成功使用Hibernate SessionFactory
对象。
I got @Autowired
to work successfully with a Hibernate SessionFactory
object by returning a FactoryBean<SessionFactory>
.
所以我的问题具体说明:对于 DataSource
,有没有办法做到这一点?或者更一般地说,在Spring Java配置中自动装配bean的方法是什么?
So my question specifically: is there a way to do that with respect to a DataSource
? Or more generally, what is the method to autowire a bean within a Spring Java Configuration?
我应该注意我使用的是Spring版本3.2。
I should note I am using Spring version 3.2.
推荐答案
如果你需要在同一个中引用
文件,只需调用bean方法。 DataSource
bean配置
If you need a reference to the DataSource
bean within the same @Configuration
file, just invoke the bean method.
@Bean
public OtherBean someOtherBean() {
return new OtherBean(dataSource());
}
或将其自动装入 @Bean
方法
@Bean
public OtherBean someOtherBean(DataSource dataSource) {
return new OtherBean(dataSource);
}
@Configuration $ c的生命周期$ c> class有时会像你建议的那样阻止自动装配。
The lifecycle of a @Configuration
class sometimes prevents autowiring like you are suggesting.
这篇关于在Spring的Java配置中自动装配bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!