在Spring的Java配置中自动连接Bean

2022-09-01 15:59:25

是否可以在用Java编写的Spring配置中使用Spring的注释?@Autowired

例如:

@Configuration
public class SpringConfiguration{

   @Autowired 
   DataSource datasource;

   @Bean
   public DataSource dataSource(){
       return new dataSource();
   }

   // ...

}

显然,数据源接口不能直接实例化,但为了简化,我在这里直接实例化了它。目前,当我尝试上述操作时,数据源对象保持空,并且不会由Spring自动连接。

我通过返回一个 .@AutowiredSessionFactoryFactoryBean<SessionFactory>

所以我的问题具体是:有没有办法做到这一点?或者更一般地说,在Spring Java配置中自动连接Bean的方法是什么?DataSource

我应该注意我正在使用Spring版本3.2。


答案 1

如果需要在同一文件中引用 Bean,只需调用 Bean 方法即可。DataSource@Configuration

@Bean
public OtherBean someOtherBean() {
    return new OtherBean(dataSource());
}

或将其自动连接到方法中@Bean

@Bean
public OtherBean someOtherBean(DataSource dataSource) {
    return new OtherBean(dataSource);
}

类的生命周期有时会像您建议的那样阻止自动布线。@Configuration


答案 2

为了完整起见:是的,从技术上讲,可以在春季@Configuration类中使用@Autowired注释,并且它的工作方式与其他弹簧豆相同。但被接受的答案显示了应该如何解决原始问题。


推荐