Struts2+Spring2框架開發的菜鳥絕對能看得懂的用戶登錄程序 (2)

struts2與spring整合,利用spring核心功能實現依賴注入。

spring:

在配置文件中應配置的bean負責給相應類的中對象成員屬性進行實例化:

1:在原有struts2項目中導入spring依賴的基本的兩個包:

spring-2.5.5.jar和struts2-spring-plugin-2.0.9.jar(由於jar過大,請自行下載)

2:給項目添加spring特性,在web.xml中添加

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</param-value>

</context-param>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

3:把struts項目中相應類中的幾個對象成員的實例化操作去掉只保留接口。

變成

private UserService userservice;

private UserDao userdao;

並一定要分別爲它們創建getter和setter

4:在spring配置文件中添加

<bean id="loginAction" class="org.action.CheckLogin">

<property name="userservice">

<ref bean="userservice"/>

</property>

</bean>

<bean id="userservice" class="org.service.impl.UserServiceImpl">

<property name="userdao">

<ref bean="userdao"/>

</property>

</bean>

<bean id="userdao" class="org.dao.impl.UserDaoImpl">

</bean>

注意這幾個bean是依次依賴的,它爲三個類中的沒有初始化的幾個屬性成員進行了初始化,

省去了在類文件中進行 UserService userservice = new UserServiceImpl()這一步。

5:在struts的配置文件中由action調用

<action name="login" class="loginAction">


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章