Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setApplicationContext(ApplicationContext applicationContext) never called

Tags:

spring

I'm trying to get the Spring application context and then call its method getBean("beanName") to get a specific bean but I'm having a null pointer exception indicating that the context is null. When I put a breakpoint inside the setApplicationContext() method, I found out that this method is never called which is weird since this method should be called after spring finishes beans instantiation. I looked for some similar questions here but none worked for me.

this is my code:

public class SpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext CONTEXT;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    public static Object getBean(String beanName){
        return CONTEXT.getBean(beanName);
    }
}
like image 614
the devops guy Avatar asked May 22 '26 08:05

the devops guy


1 Answers

Set the ApplicationContext that this object runs in.

Normally this call will be used to initialize the object.

The ApplicationContext object to be used by this object.

Add @Component.

@Component
public class SpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext CONTEXT;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CONTEXT = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return CONTEXT;
    }
}

Use ApplicationContext.

TheBeanInstance bean = SpringApplicationContext.getApplicationContext().getBean(requiredType);

ApplicationContextAware

like image 120
0gam Avatar answered May 24 '26 17:05

0gam