Cha*_*ala 0 spring servlets spring-mvc autowired
我有一个控制器(例如.MyManager),我调用组件类(bean)的方法(例如myMethod()),例如MyComponent.我有servlet,我想调用myMethod().在servlet中,我通过@Autowired注释注释了MyManager ,尽管我得到了NullPointerException.我看到了这种话题,但它对我没用.为了想象,我写了一些代码:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我使用Spring配置文件"context.xml"并获得了bean(组件)对象,但是现在我在bean对象中注入了EntityManager有问题.现在它是null,任何人都可以帮我解决这个问题吗?还更新init()方法.
public void init(ServletConfig config) throws ServletException{
ApplicationContext con = new ClassPathXmlApplicationContext("context.xml");
component = (MyComponent) con.getBean("myBean");
}
Run Code Online (Sandbox Code Playgroud)
你不能自动装配这样的依赖,因为Servlet不是Spring Beans.您需要执行以下操作:
@Override
public void init() throws ServletException {
super.init();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
component= applicationContext.getBean(MyComponent.class);
}
Run Code Online (Sandbox Code Playgroud)
同时删除@Autowired注释component
| 归档时间: |
|
| 查看次数: |
1263 次 |
| 最近记录: |