Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Spring @Value annotation in class level variables

Tags:

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.

like image 668
Paramesh Korrakuti Avatar asked Aug 12 '14 06:08

Paramesh Korrakuti


People also ask

What is the use of @value annotation 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.

Can I use @value in interface?

No, this is not (directly) possible. The default value of an annotation property must be a compile-time constant.

Can we use @value in JUnit?

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.


1 Answers

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.

like image 76
Francisco Spaeth Avatar answered Nov 03 '22 03:11

Francisco Spaeth