60

I've been breaking my head on this one. Not sure what I am missing. I am unable to get the @Value annotations to work in a pure java configured spring app(non 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;
    }
}

The property file just contains my.prop=avalue The bean is as follows:

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

The environment variable prints the value properly, the @Value does not.
avalue
Name: ${my.prop}

The main class just initializes the context.

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);

However if I use

@ImportResource("classpath:property-config.xml")

with this snippet

<context:property-placeholder location="app.properties" />

then it works fine. Of course now the enviroment returns null.

4

1 回答 1

110

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

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

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

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

于 2013-06-13T22:44:19.147 回答