ssh中整合,为什么将Action交由Spring托管,才可以在Action中使用依赖注入!
传统正确的整合方式:
struts-config.xml:
<struts-config>
<data-sources>
<form-beans>
<form-beanname="loginForm"type="com.yourcompany.struts.form.LoginForm">
</form-beans>
<action-mappings>
<action<br="">attribute="loginForm"
input="/form/login.jsp"
name="loginForm"
path="/login"
scope="request"
type="org.springframework.web.struts.DelegatingActionProxy">//使用代理
<forwardname="show"path="/show.jsp">
</action>
</action-mappings>
<message-resourcesparameter="com.yourcompany.struts.ApplicationResources">
<plug-inclassname="org.springframework.web.struts.ContextLoaderPlugIn">
<set-propertyproperty="contextConfigLocation"value="/WEB-INF/applicationContext.xml">
</plug-in>
</struts-config>
applicationContext.xml:
<beans>
<beanid="personDAO"class="com.deng.PersonDAO">
<beanname="/login"class="com.yourcompany.struts.action.LogAction">
<propertyname="personDAO"ref="personDAO">
</property>
</bean>
</beans>
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframwork.web.content.ContextLoaderListener</listener-class>
</listener>
这样一来:我想在action里面注入server,只要在action里面
privaetPersonDAOpersonDAO;
publicPersonDAOgetPersonDAO(){
returnpersonDAO;
}
publicvoidsetPersonDAO(PersonDAOpersonDAO){
this.personDAO=personDAO;
}
就可以拿到personDAO对象想干吗就干吗了。。
我的问题是:
我前几天一个不小心有个问题没弄明白:为什么将Action交由Spring托管,才可以在Action中使用依赖注入!
我的:
struts-config.xml:
<action-mappings>
<action<br="">attribute="loginForm"
input="/form/login.jsp"
name="loginForm"
path="/login"
scope="request"
type="com.yourcompany.struts.action.LogAction">//不使用代理
<forwardname="show"path="/show.jsp">
</action>
applicationContext.xml:
<beans>
<beanid="personDAO"class="com.deng.PersonDAO">
<beanname="/login"class="com.yourcompany.struts.action.LogAction">//就象和<beanid="personDAO"class="com.deng.PersonDAO">一样<propertyname="personDAO"ref="personDAO">
</property>
</bean>
</beans>
然后在action里面
privaetPersonDAOpersonDAO;
..get()和..set()居然拿到的personDAO是空。为什么??
为什么:<beanid="personDAO"class="com.deng.PersonDAO">直接在spring里面直接写可以,而action非要托管才能注入,不能象server啊dao之类的直接在applicationContext.xml里面写配置。
因为Action类不是普通的类似于我们自己写的dao层或者service层的类,
它是由Struts框架来支持产生的,所以说不能简单的用类似于dao层或者service层
的依赖注入方式来,所以要使用Spring中的DelegatingActionProxy(授权Action代理),实现了针对实际Action的调用代理,struts最终调用的将是由
spring管理的Action实例,这样客户端发送的各种请求就可以用spring的Ioc设计思
想实现了。
详细的可以百度一下DelegatingActionProxy的意思,其实本身struts框架中也包含这个的。