Saturday, January 30, 2021

Why can't you use @Autowired with static fields?

Because when the class loader loads the static values, the Spring context is not yet necessarily loaded. So the class loader won't properly inject the static fields in the bean and will fail.

https://stackoverflow.com/questions/10938529/why-cant-we-autowire-static-fields-in-spring/21875258#21875258


Its basically an "ANTI-PATTERN", Still we have a hack to work around this limitation, Here it is.

https://stackoverflow.com/questions/1018797/can-you-use-autowired-with-static-fields/5991240#5991240

@Component("NewClass")
public class NewClass{
    private static SomeThing someThing;

    @Autowired
    public void setSomeThing(SomeThing someThing){
        NewClass.someThing = someThing;
    }
}

No comments:

Post a Comment

Azure - Pipeline - Add Approver for Stage

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/approvals?view=azure-devops&tabs=check-pass