I need to use injected parameter by @Value
in instance variable of a class and can be reused that variable in all its child classes.
@Value(server.environment)
public String environment;
public String fileName = environment + "SomeFileName.xls";
Here, the problem is fileName initializing first and then environment injection is happening. So I am getting always null-SomeFileName.xls.
Anyway to convey to initialize first @Value
in spring.
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.
No, this is not (directly) possible. The default value of an annotation property must be a compile-time constant.
With the @ValueSource annotation, we can pass an array of literal values to the test method. As we can see, JUnit will run this test two times and each time assigns one argument from the array to the method parameter.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With