Java 如何使用注释在Spring中加载系统属性?
我对Spring有一个问题,我必须使用注释加载系统属性 我正在尝试这种方法:Java 如何使用注释在Spring中加载系统属性?,java,spring,spring-mvc,Java,Spring,Spring Mvc,我对Spring有一个问题,我必须使用注释加载系统属性 我正在尝试这种方法: @Value("${mySystemProperty}") private String mySystemPropertyValue; 但当我这样做的时候: System.out.println("mySystemPropertyValue="+mySystemPropertyValue); System.out.println("system.mySystemProperty="+System.getPropert
@Value("${mySystemProperty}")
private String mySystemPropertyValue;
但当我这样做的时候:
System.out.println("mySystemPropertyValue="+mySystemPropertyValue);
System.out.println("system.mySystemProperty="+System.getProperty("mySystemProperty"));
它返回:
mySystemPropertyValue=null
system.mySystemProperty=myValue
怎么了
谢谢
编辑
我尝试了所有方法,但我总是为每个系统属性返回一个空值
我还尝试:
@Autowired
private Environment environment;
但是“环境”变量为空…请尝试以下操作:
@配置
@启用Web安全性
@EnableGlobalMethodSecurity(Prespenabled=true,securedEnabled=true,proxyTargetClass=true)
公共类SecurityContextConfig扩展了WebSecurity配置适配器
{
@值(“#{systemProperties['your.system.property']}”)
私有财产;
...
}
您的配置类似乎包含一些BeanFactoryPostProcessor
。我相信它是propertysourcesplaceconfigurer
,因为您需要这个bean来解析属性
Spring javadoc的一些解释:
必须特别考虑返回SpringBeanFactoryPostProcessor(BFPP)类型的@Bean方法。由于BFPP对象必须在容器生命周期的早期进行实例化,因此它们可能会干扰@Configuration类中@Autowired、@Value和@PostConstruct等注释的处理。为了避免这些生命周期问题,将返回@Bean方法的BFPP标记为静态
这就是为什么@Autowired
和@Value(“#{systemProperties['your.system.property']}”)
不能在config类中工作的原因。
因此,要解决您的问题,只需创建返回
propertySourcesplaceConfigurer
静态的方法,或者如果您没有该方法,则添加该方法
@Bean
public static PropertySourcesPlaceholderConfigurer pspc() {
return new PropertySourcesPlaceholderConfigurer();
}
并确保不再有返回@Bean方法的非静态BFPP。
您还可以将BFPP bean移动到单独的@Configuration
类
更新
演示
@Value
在@Configuration
@Configuration
public class SimpleJavaConfig {
@Value("${java.version}")
private String property;
public static void main(String[] args) throws IOException {
ApplicationContext app = new AnnotationConfigApplicationContext(SimpleJavaConfig.class);
System.out.println("|" + app.getBean("propertyBean") + "|");
}
@Bean
public static PropertySourcesPlaceholderConfigurer pcc() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public String propertyBean() {
return property;
}
}
试试这个:
System.out
放在哪里?还有Spring管理bean上的@Value
,或者只是一个普通的东西。我尝试了@Value(#{systemproperty['myystemproperty']})和@Value(#{systemproperty.myystemproperty}),但我总是得到null作为回报。我的属性名有一个“-”字符(确切的名称是“我的属性”)。但我不认为这取决于它…尝试过它,但它不起作用。谢谢你的回答,但我不明白如何使用bean PropertySourcesPlaceholderConfigurer读取属性。你能给我一个主意吗?Thanks@AlessandroC您不需要使用属性资源占位符配置器
任何特殊功能。只要将它添加到上下文中,它就会解析属性值。这个bean是使@Value(${mySystemProperty}”)
工作所必需的。我已经像您的指示一样添加了这个bean,但是如果我尝试用@Value(${myProperty})创建一个变量,它仍然返回null。。。我不明白为什么@AlessandroC您是否以某种方式传递了my property
值?e、 g.-Dmy财产=myValue@AlessandroC我在答案中添加了一个简单的例子。试试看