BadPractice2 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki
Bad Practice - Injected a Value to static field
Description
Injected a value from a Java properties file to a static field with Spring will have some workarounds.
The first one is to Create a setter method and annotate it with the @Value
annotation. Here is the example:
@Controller
public class PropertyController {
@Value("${name}")
private String PARAM;
private static String PARAM_STATIC;
@Value("${name}")
public void setParamStatic(String PARAM){
PropertyController.PARAM_STATIC = PARAM;
}
}
The second one is to use @PostConstruct
annotation. It will be called once after the initialization of bean properties. Here is the example:
public class Sample {
@Value("${my.name}")
private String PARAM;
public static String PARAM_STATIC;
@PostConstruct
public void init(){
PARAM = PARAM_STATIC;
}
}
The third is to use Constructor @Autowired For Static Field.
(Need to add more)
Reason
Solution
(I will do more investigation for trying to find a solution. For now, it's advised that create a second class with private
field and getter instead of publib static
field)
References
- Baeldung - Injecting a Value in a Static Field in Spring
- Stack Overflow - Spring: How to inject a value to static field?
- Baeldung - Spring PostConstruct and PreDestroy Annotations
- CodezUp - @Autowired with Static Method in Spring | Spring Boot | Java