Accessing spring beans in static method

My approach is for the bean one wishes to access to implement InitializingBean or use @PostConstruct, and containing a static reference to itself.

For example:

@Service
public class MyBean implements InitializingBean {
    private static MyBean instance;

    @Override
    public void afterPropertiesSet() throws Exception {
        instance = this;
    }

    public static MyBean get() {
        return instance;
    }
}

Usage in your static class would therefore just be:

MyBean myBean = MyBean.get();

This way, no XML configuration is required, you don’t need to pass the bean in as a constructor argument, and the caller doesn’t need to know or care that the bean is wired up using Spring (i.e., no need for messy ApplicationContext variables).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)