gpt4 book ai didi

java - 带有纯 java 配置的 Spring 3.2 @value 注释不起作用,但 Environment.getProperty 有效

转载 作者:IT老高 更新时间:2023-10-28 13:02:35 26 4
gpt4 key购买 nike

在这个问题上我一直很头疼。不知道我错过了什么。我无法让 @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;
}
}

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

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

环境变量正确打印值,@Value没有。

名称:${my.prop}

主类只是初始化上下文。

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);

但是如果我使用

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

这个片段

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

然后它工作正常。当然现在环境返回 null

最佳答案

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

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

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

@PropertySource文档和这个 Spring Framework Jira issue .

关于java - 带有纯 java 配置的 Spring 3.2 @value 注释不起作用,但 Environment.getProperty 有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17097521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com