BadPractice3 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki
Bad Practice - Used @Autowired with Static Fields
Description
There are two workarounds to use @Autowired
with static fields, but these two approches are not good practices.
The first one is to Create a setter method and annotate it with the @Value
annotation. Here is the example:
@Component
public class PropertyController {
private static String PARAM_STATIC;
@Autowired
public void setParamStatic(String PARAM_STATIC){
PropertyController.PARAM_STATIC = PARAM_STATIC;
}
}
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 {
@Autowired
private String PARAM;
public static String PARAM_STATIC;
@PostConstruct
public void init(){
PARAM = PARAM_STATIC;
}
}
Reason
(reasons for static values and Spring context, need to dive into it)
Solution
The same as the other bad practice.
References
- Stack Overflow - Can you use @Autowired with static fields?
- Stack Overflow - Why can't we autowire static fields in spring?