[英]Spring @Value can not get system property
import org.springframework.beans.factory.annotation.Value;
public class PropertyReader {
@Value("${spring.active.profiles")
private String profile;
@Nonnull
public String getProfile() {
return profile;
}
}
这是我的测试
public class PropertyReaderTest {
@Test
public void testGetProfile() throws Exception {
System.out.printf(System.getProperty("spring.active.profiles"));
assertEquals("development", new PropertyReader().getProfile());
}
}
我的依赖是
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
</dependencies>
我看到
development
java.lang.AssertionError:
Expected :development
Actual :null
我首先假设您的语法正确,并且您输入的@value类型错误。
@Value("${spring.active.profiles}")
现在要使用@value,必须使该类注册为spring bean,并且也仅使用注释。 即使您使用xml注册类,您的@value也将不起作用。
并且还可以使用spring容器获取自动发生的bean,不要使用new自己创建对象。
解决上述问题
1)
@Component
PropertyReader
使用@Component将类PropertyReader用作spring bean。
2)从测试类的应用程序上下文中加载bean,不要使用new来创建它。
Yuo应该将@Service放在PropertyReader类上,或者您应该使用XML spring文件来定义bean并让spring来实现属性的价位化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.