使用纯java配置的Spring 3.2 @value注释不起作用,但Environment.getProperty可以工作

Abe*_*Abe 55 java spring

我一直在打破这个问题.不确定我错过了什么.我无法@Value在纯java配置的spring应用程序(非web)中使用注释

@Configuration
@PropertySource("classpath:app.properties")
public class Config {
    @Value("${my.prop}") 
    String name;

    @Autowired
    Environment env;

    @Bean(name = "myBean", initMethod = "print")
    public MyBean getMyBean(){
         MyBean myBean = new MyBean();
         myBean.setName(name);
         System.out.println(env.getProperty("my.prop"));
         return myBean;
    }
}
Run Code Online (Sandbox Code Playgroud)

属性文件只包含my.prop=avaluebean如下:

public class MyBean {
    String name;
    public void print() {
        System.out.println("Name: " + name);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

环境变量正确打印值,而@Value不是.
avalue
Name: ${my.prop}

主类只是初始化上下文.

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用

@ImportResource("classpath:property-config.xml")
Run Code Online (Sandbox Code Playgroud)

用这个片段

<context:property-placeholder location="app.properties" />
Run Code Online (Sandbox Code Playgroud)

然后它工作正常.当然现在环境又回来了null.

dim*_*hez 104

在您的Config类中添加以下bean声明

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
Run Code Online (Sandbox Code Playgroud)

为了使@Value注释工作,PropertySourcesPlaceholderConfigurer应该注册.它<context:property-placeholder>在XML中使用时自动完成,但应static @Bean在使用时注册@Configuration.

请参阅@PropertySource文档和此Spring Framework Jira问题.

  • +1 - 令人尴尬的是,在开始一个新项目时,我似乎总是忘记这一点,而且我每次都会找到这个答案. (12认同)
  • 这很棒!春天的文档@Configuration错过了这个.导致所有这些混乱 (2认同)
  • 将 bean 注册为“静态”是我的关键。谢谢。 (2认同)