简体   繁体   English

Spring @Value 无注释

[英]Spring @Value without annotation

Instead of using @Value doing this:而不是使用@Value这样做:

@Service
public class MyService{
    @Value("${myValue}")
    private String myValue;
}

I need to get ${myValue} without annotation, and without reading the file again.我需要在没有注释的情况下获取${myValue} ,并且无需再次读取文件。 How to do it?怎么做?

You can get it from Environment :您可以从Environment获得它:

@Autowired
private Environment env;
// ... 
env.getProperty("myValue");

One way to access Environment is through EnvironmentAware interface.访问Environment的一种方法是通过EnvironmentAware接口。

Example:例子:

@Service
public class MyService implements EnvironmentAware{

    private String myValue;
    private Environment env;

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }

    public String getMyValue() {
        return env.getProperty("myValue");
    }
}

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

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