Question

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");
}
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top