Does environment.getProperty("property") produces the same value as @Value("property")

vladwoguer :

I'm refactoring a project and on one of the services I found this piece of code:

@Service
public class MyService {   
    private String API_PORT;


    public JenkinsService(final Environment environment) {
        this.API_PORT = environment.getProperty("server.port");
    }
}

My doubt is if I can change it to the following code (Using @Value) without unexpected behavior:

@Service
public class MyService {   
    @Value("${server.port}")
    private String API_PORT;


    public JenkinsService() {}
}
davidxxx :

Environment expose all properties, you generally don't want that.
Besides, it exposes also information about profiles (distinguishing which activated and all) which here you don't care.

Property placeholder ${...} should always be favored to injecting Environment instance but for fair reasons as stated by the Environment javadoc (emphasis is mine) :

In most cases, however, application-level beans should not need to interact with the Environment directly but instead may have to have ${...} property values replaced by a property placeholder configurer such as PropertySourcesPlaceholderConfigurer, which itself is EnvironmentAware and as of Spring 3.1 is registered by default when using .

And not directly your question, but constructor injection should be favored over field injection that encourages opaque and flawed design :

public class MyService {   

    private final String apiPort;

    public MyService (@Value("${server.port}") String apiPort){
        this.apiPort = apiPort;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309271&siteId=1