How to use Spring @Value annotation in class level variables
You can use @PostConstruct
therefore. From documentation:
The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization.
@PostConstruct
allows you to perform modification after properties were set. One solution would be something like this:
public class MyService {
@Value("${myProperty}")
private String propertyValue;
@PostConstruct
public void init() {
this.propertyValue += "/SomeFileName.xls";
}
}
Another way would be using an @Autowired
config-method. From documentation:
Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.
...
Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter methods are effectively just a special case of such a general config method. Such config methods do not have to be public.
Example:
public class MyService {
private String propertyValue;
@Autowired
public void initProperty(@Value("${myProperty}") String propertyValue) {
this.propertyValue = propertyValue + "/SomeFileName.xls";
}
}
The difference is that with the second approach you don't have an additional hook to your bean, you adapt it as it is being autowired.