Spring: How to enter a value in a static field?

With this class

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

If I try Sample.name , it will always be "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 set correctly. Is this a good way or not? If not, is there something better? And how to do it?

+35
spring code-injection
Aug 31 '11 at 7:12
source share
1 answer

In general, public static not the final field of evil . Spring does not allow such fields to be entered for any reason.

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

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

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

+52
Aug 31 '11 at 7:18
source share



All Articles