Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: How to inject a value to static field?

With this class

@Component public class Sample {      @Value("${my.name}")     public static String name;   } 

If I try Sample.name, it is always 'null'. So I tried this.

public class Sample {      public static String name;      @PostConstruct     public void init(){         name = privateName;     }      @Value("${my.name}")     private String privateName;      public String getPrivateName() {         return privateName;     }      public void setPrivateName(String privateName) {         this.privateName = privateName;     }    } 

This code works. Sample.name is set properly. Is this good way or not? If not, is there something more good way? And how to do it?

like image 511
Whiteship Avatar asked Aug 31 '11 07:08

Whiteship


People also ask

How do you inject a value to a static field?

Solution First, PropertyController, which is a RestController, is being initialized by Spring. Afterward, Spring searches for the Value annotated fields and methods. Spring uses dependency injection to populate the specific value when it finds the @Value annotation.

How do you inject Spring values?

Method 3 : Using @Value annotation This method involves applying @Value annotation over bean properties whose values are to be injected. The string provided along with the annotation may either be the value of the bean field or it may refer to a property name from a properties file loaded earlier in Spring context.

Can we use @autowired in static variable?

In short, no. You cannot autowire or manually wire static fields in Spring.


1 Answers

First of all, public static non-final fields are evil. Spring does not allow injecting to such fields for a reason.

Your workaround is valid, you don't even need getter/setter, private field is enough. On the other hand try this:

@Value("${my.name}") public void setPrivateName(String privateName) {     Sample.name = privateName; }   

(works with @Autowired/@Resource). But to give you some constructive advice: Create a second class with private field and getter instead of public static field.

like image 189
Tomasz Nurkiewicz Avatar answered Sep 23 '22 05:09

Tomasz Nurkiewicz