Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从JBoss中的servlet访问Springbean_Java_Spring_Jakarta Ee_Servlets_Jboss - Fatal编程技术网

Java 从JBoss中的servlet访问Springbean

Java 从JBoss中的servlet访问Springbean,java,spring,jakarta-ee,servlets,jboss,Java,Spring,Jakarta Ee,Servlets,Jboss,我想在JBoss中编写一个简单的servlet,它将调用Springbean上的一个方法。其目的是允许用户通过点击URL启动内部作业 在servlet中获取对我的Springbean的引用的最简单方法是什么 JBoss web服务允许您使用@Resource注释将WebServiceContext注入到服务类中。在普通servlet中是否有类似的功能?解决此特定问题的web服务将使用大锤敲碎螺母。我找到了一种方法: WebApplicationContext context = WebAppli

我想在JBoss中编写一个简单的servlet,它将调用Springbean上的一个方法。其目的是允许用户通过点击URL启动内部作业

在servlet中获取对我的Springbean的引用的最简单方法是什么


JBoss web服务允许您使用@Resource注释将WebServiceContext注入到服务类中。在普通servlet中是否有类似的功能?解决此特定问题的web服务将使用大锤敲碎螺母。

我找到了一种方法:

WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
SpringifiedJobbie jobbie = (SpringifiedJobbie)context.getBean("springifiedJobbie");

您的servlet可以使用WebApplicationContextUtils来获取应用程序上下文,但是您的servlet代码将直接依赖于Spring框架

另一个解决方案是配置应用程序上下文,将Springbean作为属性导出到servlet上下文:

<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
  <property name="attributes">
    <map>
      <entry key="jobbie" value-ref="springifiedJobbie"/>
    </map>
  </property>
</bean>

有一种更复杂的方法可以做到这一点。
org.springframework.web.context.support
中有
SpringBeanAutowiringSupport
允许您构建如下内容:

public class MyServlet extends HttpServlet {

  @Autowired
  private MyService myService;

  public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
      config.getServletContext());
  }
}

这将导致Spring查找与该
ServletContext
关联的
ApplicationContext
(例如,通过
ContextLoaderListener
创建),并在该
ApplicationContext
中注入可用的Spring bean,这样做不使用WebApplicationContext有什么好处?无论哪种方式,它都与Spring绑定。填充servlet上下文属性的机制不必使用Spring实现。启动时运行的筛选器或其他servlet可以填充servlet上下文属性;它会自动处理其余的。如果您需要访问任何ServletConfig,请确保在“init”方法中调用“super.init(config)”;e、 g.public void init(ServletConfig config){super.init(config);SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,config.getServletContext();}在servlet中使用实例变量存在已知的数据访问竞争条件风险(如果不遵循SingleThreadModel)。我相信如果实例变量是自动连接的,那么风险仍然存在。OWASP链接:
public class MyServlet extends HttpServlet {

  @Autowired
  private MyService myService;

  public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
      config.getServletContext());
  }
}