使用Spring的注解方式注入Struts所管理的action

因为集成SSH框架时,常容易出错,所以一般要加上log4j日志文件,来显示错误信息(log4j.properties放在源文件目录下,log4j.jar放在WEB-INF/lib目录下)

首先要加载Spring,一般有三种加载方式:

一.插件方式,struts启动时启动spring

struts配置文件struts-config.xml中增加如下配置:

<plug-in   className="org.springframework.web.struts.ContextLoaderPlugIn">

      <set-property property="contextConfigLocation"

        value="classpath*:applicationContext*.xml" />

plug-in>

 

二.Servelt方式或者Listener,在web容器启动时启动

在web.xml中:

   contextConfigLocation

   classpath*:applicationContext*.xml

 

      

org.springframework.web.context.ContextLoaderListener

 

   startspring   org.springframework.web.context.ContextLoaderServlet

   0

 

然后需要在struts-config.xml中配置(这里要注意代码的顺序):


 
     value="org.springframework.web.struts.DelegatingRequestProcessor" />
 

 

 

然后再applicationContext中配置:


 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
 
 
 

 
 
 
   base-package="com.aptech.jb.epet.aop.aspects" />
 

 
   class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  
   classpath:hibernate.cfg.xml
  

 

 

 
   class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  
 

 
 
 
 
 
 
 
 
 
 

 

 
 
 

这里要注意bean里的name值要和struts里的path 相同

 

最后在相关action中注入依赖的biz,这里采用注解的方式

 

public class LoginAction extends Action {
 @Resource
 private PetInfoBiz petInfoBiz;

 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  ..........省略

}

OK!

 

你可能感兴趣的:(java)