简体   繁体   English

Spring @Value无法获取系统属性

[英]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;
    }
}

and this is test I have 这是我的测试

public class PropertyReaderTest {

    @Test
    public void testGetProfile() throws Exception {
        System.out.printf(System.getProperty("spring.active.profiles"));
        assertEquals("development", new PropertyReader().getProfile());
    }
}

and the dependency I have is 我的依赖是

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.3.RELEASE</version>
        </dependency>
    </dependencies>

and I see 我看到

development
java.lang.AssertionError: 
Expected :development
Actual   :null

first thing i am assuming your syntax is correct and its type mistake for @value that you have posted. 我首先假设您的语法正确,并且您输入的@value类型错误。

 @Value("${spring.active.profiles}")

Now to use @value, you must make the class register as a spring bean and that too using only annotation. 现在要使用@value,必须使该类注册为spring bean,并且也仅使用注释。 even if you register class using xml also your @value will not work. 即使您使用xml注册类,您的@value也将不起作用。

and also get the bean using spring container to happen automatic injection, dont create object by yourselves using new. 并且还可以使用spring容器获取自动发生的bean,不要使用new自己创建对象。

Solution to your above problem 解决上述问题

1) 1)

@Component
PropertyReader 

make class PropertyReader as a spring bean using @Component. 使用@Component将类PropertyReader用作spring bean。

2)load bean from application context in your test class, dont use new to create it. 2)从测试类的应用程序上下文中加载bean,不要使用new来创建它。

Yuo应该将@Service放在PropertyReader类上,或者您应该使用XML spring文件来定义bean并让spring来实现属性的价位化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM