setApplicationContext(ApplicationContext applicationContext) never called - 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);
}
}

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

Related

how to convert BeanFactory to ApplicationContext

I have some code like this:
#Slf4j
#Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
ListableBeanFactory listableBeanFactory = factory;
ApplicationContext applicationContext = (ApplicationContext) listableBeanFactory;
AbstractApplicationContext context = (AbstractApplicationContext) applicationContext;
ConfigurableEnvironment environment = context.getEnvironment();
AbstractEnvironment abstractEnvironment = (AbstractEnvironment) environment;
abstractEnvironment.getProperty("business.bean.dependsOn");
// how to gain ApplicationContext
//.........
}
I want to obtain some config value from classpath:application.properties
and only ApplicationContext could getEnvironment.
how to gain ApplicationContext?
The ApplicationContext object can be obtained by implementing the ApplicationContextAware interface.
The Value annotation gets the attributes in application.properties.

How to get ApplicationContext inside a unit test class of non-spring managed class

I have a requirement where I had to use Spring beans inside a POJO class to retrieve a MyDomainClass object. Since Autowiring the beans inside the class which is not managed by Spring isn't possible, I had to explicitly get the ApplicationContext from another util class and retrieve the bean from applicationContext object. Please find the code below
#Component
public class ApplicationContextUtils implements ApplicationContextAware{
private static ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
applicationContext = appContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
The code for using the applicationContext and retrieving the bean is below
public class MyNonBeanClass{
public MyDomainClass retrieveMyDomainObj(){
ApplicationContext applicationContext=ApplicationContextUtils.getApplicationContext();
TestBean testBean=(TestBean)applicationContext.getBean("testBean");
return testBean.retrieve(param1,param2);
}
}
This code is working as expected and I am able to fetch the beans from the application context successfully. But writing the test case has been challenging to say the least. I am not even sure if we will be able to write the test case for my non bean class but I would still like to try. I am trying to use PowerMock to mock the static invocation of getApplicationContext() in ApplicationContextUtils. But I am unable to get the applicationContext necessary for getting the TestBean object. And a NullPointerException is thrown when the getBean() is called on applicationContext. Please help with this.
#RunWith(PowerMockRunner.class)
#PrepareForTest(ApplicationContextUtils.class)
#ContextConfiguration(classes= { BaseTestContext.class})
public class MyNonBeanClassTest implements ApplicationContextAware{
MyNonBeanClass myNonBeanClass;
ApplicationContext applicationContext;
#Test
public void test_retrieveMyDomainObj(){
myNonBeanClass=new MyNonBeanClass();
PowerMockito.mockStatic(ApplicationContextUtils.class);
when(ApplicationContextUtils.getApplicationContext()).thenReturn(applicationContext);
assertNotNull(myNonBeanClass.retrieveMyDomainObj(param1, param2));
}
#Override
public void setApplicationContext(ApplicationContext appContext) throws BeansException {
// TODO Auto-generated method stub
this.applicationContext=appContext;
}
public ApplicationContext getApplicationContext(){
return this.applicationContext;
}
}

why invoking a service in my servlet gives me an NPE (spring)

I have defined a service in Spring
#Service("StockageService")
public class StockageServiceImpl implements StockageService{
}
with
public interface StockageService extends Serializable {
}
And I need in a servlet to invoke this service
So I wrote
public class SpringApplicationContextListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
sce.getServletContext().setAttribute("applicationContext", ac);
}
public void contextDestroyed(ServletContextEvent sce) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
And
public class handler extends HttpServlet {
private String message;
private StockageService stockageService;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext ac = (ApplicationContext) config.getServletContext().getAttribute("applicationContext");
this.stockageService = (StockageService)ac.getBean("StockageService");
}
The problem is that I get a NPE at the last mentionned line
(StockageService)ac.getBean("StockageService");
Where could I have made a mistake ?
First, thanks ankur-singhal for having taken the time to answer my question
I understand the reasonnement of your answer but it does not work when I invoke
ApplicationContextUtils. getApplicationContext().getBean("StockageService");
So I used a trick which works but I do not understand very well
I override the init in my servlet as it follows
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
and I have to put a
#Autowired
private StockageService stockageService;
in the servlet and it works
It seems that ApplicationContext itself is comming as null.
Look at below code and try make use of this.
ApplicationContextUtils.java
We will create the following utility class, it implements ApplicationContextAware and provides the setApplicationContext which will be invoked by spring container and the applicationContext will be passed by it. We store it in a static variable and expose it through a get method so that it can be accessed all through the application.
You can set the same while creating ApplicationContext
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext ctx;
#Override
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
ctx = appContext;
}
public static ApplicationContext getApplicationContext() {
return ctx;
}
}

Access spring component from servlet

I have a controller (for example. MyManager) where I invoke method (for example myMethod() ) of component class (bean), for example MyComponent. I have I servlet where I want to invoke myMethod() . In servlet I have annotated MyManager by #Autowired annotation , despite this I got NullPointerException. I saw this kind of topic but it is not useful for me. For imagination I write little code :
public class myClass extends HttpServlet {
#Autowired
private MyComponent component;
public void init(ServletConfig config) throws ServletException{
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ... {
List<MyObject> objects =component.myMethod(); // Here is the problem, component is null
}
}
}
I make Spring configuration file "context.xml" and I got bean (component) object, but now I have problem with injected EntityManager in bean object. Now it is null , can anyone help me to solve this problem ? Also update init() method.
public void init(ServletConfig config) throws ServletException{
ApplicationContext con = new ClassPathXmlApplicationContext("context.xml");
component = (MyComponent) con.getBean("myBean");
}
You cannot autowire dependencies like that because Servlets are not Spring Beans. You need to do something like the following:
#Override
public void init() throws ServletException {
super.init();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
component= applicationContext.getBean(MyComponent.class);
}
Also drop the #Autowired annotation from component

How to use the appicationcontextaware in java class

I need to load the applicationcontext in java class in which the applicationcontextaware bean is defined. I need to access the other beans inside the applicationcontext.xml using the applicationcontextaware. I dont want to load the context using
ClassPathXmlApplicationContext("applicationContext.xml");
I need to access the beans inside the applicationContext like this
ApplicationContextAccess.getInstance().getApplicationContext.getbean("BeanName");
Applicationcontextacess implemented as singleton class:
public class ApplicationContextAccess implements ApplicationContextAware {
private ApplicationContext applicationContext = null;
private static ApplicationContextAccess applicationContextAccess=null;
private ApplicationContextAccessor() {
}
public static synchronized ApplicationContextAccess getInstance() {
if(applicationContextAccess == null)
{
applicationContextAccess = new ApplicationContextAccess();
}
return applicationContextAccess;
}
public void ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext = applicationContext;
}
}
I need to access the beans inside the applicationContext like this ApplicationContextAccess.getInstance().getApplicationContext.getbean("BeanName");
But I have a doubt how the getApplicationContext loads the applicationContext.xml........?

Resources