Autowire a bean within Spring's Java configuration

后端 未结 4 2028
庸人自扰
庸人自扰 2020-12-03 04:51

Is it possible to use Spring\'s @Autowired annotation within a Spring configuration written in Java?

For example:

@Configuration
public          


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 05:28

    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());
    }
    

    or have it autowired into the @Bean method

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

    The lifecycle of a @Configuration class sometimes prevents autowiring like you are suggesting.

提交回复
热议问题