Autowire a bean within Spring's Java configuration

后端 未结 4 1994
庸人自扰
庸人自扰 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:22

    For completeness sake: Yes it is technically possible to use @Autowired annotation in spring @Configuration classes, and it works the same way as for other spring beans. But the accepted answer shows how the original problem should be solved.

    0 讨论(0)
  • 2020-12-03 05:25

    beans configured with @Configuration class can't be autowired ,

    So you cannot use @Autowiring and @configuration together

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 05:29

    maybe you can use constructor to inject some bean from other configuration file to your configuration,while @Autowired may not work correct in the configuration file

    @Configuration
    public class AppConfig {
      private DataSource dataSource;
    
      public AppConfig(DataSource dataSource) {
        this.dataSource = dataSource;
      }
    
      @Bean
      public OtherBean otherBean(){
        return new OtherBean(dataSource);
      }
    }
    
    0 讨论(0)
提交回复
热议问题