@ Configuration-annotated类中的Autowired Environment为空

时间:2017-01-26 12:38:11

标签: spring

在此@Configuration - 带注释的类中,@Autowired Environment类始终为null。

以下代码示例直接取自: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html

 @Configuration
 @PropertySource("classpath:/com/myco/app.properties")
 public class AppConfig {

     @Autowired
     Environment env;

     @Bean
     public TestBean testBean() {
         TestBean testBean = new TestBean();
         // some futher contitional stuff/checks etc. on the properties 
         String someProp = env.getProperty(...);
         if(someProp.equals(...)) {
             ...
         }
         return testBean;
     }
 }

如果我使用类EnvironmentAwareEnvironment设置正确(我的代码可以正常工作)。

 @Configuration
 @PropertySource("classpath:/com/myco/app.properties")
 public class AppConfig implements EnvironmentAware {

     Environment env;

     @Bean
     public TestBean testBean() {
         // ...
     }

     @Override
     public void setEnvironment(final Environment environment) {
         this.environment = environment;
     }
 }

任何想法为什么@Autowired方法在@Configuration - 注释类中不起作用,因为自动装配其他bean中的Environment

2 个答案:

答案 0 :(得分:0)

我认为您必须向@Bean课程添加Environment注释,因为如果您希望@Autowired课程未签名为@Bean,那么这是不可能的

答案 1 :(得分:0)

尝试直接注入值:

@Configuration
 @PropertySource("classpath:/com/myco/app.properties")
 public class AppConfig {

    @Value("${testbean.name}")
    private String testbeanName;

    @Bean
    public TestBean testBean() {
       TestBean testBean = new TestBean();
       testBean.setName(testbeanName);
       return testBean;
    }
 }