【问题标题】:Access spring component from servlet从 servlet 访问 spring 组件
【发布时间】:2014-05-29 22:45:43
【问题描述】:

我有一个控制器(例如。MyManager),我在其中调用组件类(bean)的方法(例如 myMethod() ),例如 MyComponent。我有我想调用 myMethod() 的 servlet。在 servlet 中,我用 @Autowired annotation 注释了 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

}

}

}

我制作了 Spring 配置文件“context.xml”并获得了 bean(组件)对象,但现在我在 bean 对象中注入 EntityManager 时遇到问题。现在它是空的,任何人都可以帮我解决这个问题吗?还要更新 init() 方法。

public void init(ServletConfig config) throws ServletException{
ApplicationContext con = new ClassPathXmlApplicationContext("context.xml");
component = (MyComponent) con.getBean("myBean");
}

【问题讨论】:

  • 请发布 context.xml
  • 谢谢我用另一种方式解决了问题,没有 servlet。非常感谢:)

标签: spring spring-mvc servlets autowired


【解决方案1】:

你不能像这样自动装配依赖关系,因为 Servlet 不是 Spring Bean。您需要执行以下操作:

@Override
public void init() throws ServletException {
    super.init();
    ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    component= applicationContext.getBean(MyComponent.class);
}

同时从component 中删除@Autowired 注释

【讨论】:

  • 为此我需要 application-context.xml 文件吗?
  • 您需要以某种方式定义 Spring 上下文,最有可能使用 application-context.xml
  • 在我的项目中创建 application-context.xml 文件可以吗?或者你能指出我在哪里可以看到如何定义 Spring Context 的来源?
  • If 是定义 Spring 上下文的绝佳方式。 viralpatel.net/blogs/…
  • 最好不要使用 Servlet,除非你真的需要它们,而是使用 Spring MVC 控制器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2014-02-20
  • 1970-01-01
  • 2012-12-22
  • 1970-01-01
  • 2014-01-14
  • 2011-05-02
相关资源
最近更新 更多