最近發現,我對於ssh的 自動注入配置 還是不熟悉,於是整理了一下 終於做了一個 簡單的 注入配置出來。 以前都是在applicationContext.xml 里面這樣配
<bean id="loginAction" class="com.dj.ssh.action.LoginAction" scope="prototype" autowire="byName"> <property name="userService" ref="userService"></property> </bean> <bean id="userService" class="com.dj.ssh.service.impl.UserServiceImpl"> <property name="userDAO" ref="userDAO"></property> </bean> <bean id="userDAO" class="com.dj.ssh.dao.impl.UserDaoImpl"> <property name="sessionFactory" ref="mySessionFactory"></property> </bean
后來發現,mdzz,直接注入service,注入就可以了。
於是就有了這篇ssh框架最簡單配置。
新手可以看一下。 我將從 用myeclipse 生成ssh框架 的第一步 一直講到 注入 service
環境:myeclipse 8.5,用eclipse的插件如何快速生成ssh項目,還是自行百度吧 (其實大部分博主這個時候會說的是 :請參考我另一篇博文)
好,新建web項目,項目名稱demo
<!--配置 spring 配置文件的位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--配置 spring監聽器 --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
接着配置 applicationContext.xml
此時,由於我們是自動生成的 所以 在src目錄下的applicationContext.xml 文件中 已經有很多代碼了。 我們不用管他
隨便在開頭還是末尾 加上三行關鍵的代碼就可以了
<!-- 打開自動裝配--> <context:annotation-config></context:annotation-config> <!-- 設置掃描路徑 配置了以后,他會 自動掃描com.service.*.* 路徑下的所有的包 --> <context:component-scan base-package="com" use-default-filters="false"> <context:include-filter type="regex" expression="com.service.*.*"/> </context:component-scan>
接着 配置 struts.xml 文件
<package name="login" extends="struts-default"> <action name="login" class="com.action.UserAction"> <result name="success">index.html</result> </action> </package>
此時 當我在瀏覽器里輸入http://localhost:8080/demo/login.action 的時候 他會通過struts 轉發去com.action.UserAction 文件下
UserAction 返回success 的話 就 跳轉到index.html 頁面
com.action.UserAction 代碼
public class UserAction extends ActionSupport{ private UserService service; //Autowired 通過set方法自動裝配 service @Autowired public void setservice(UserService userservice) { this.service = userservice; } @Override public String execute() throws Exception { service.login(); if(service!=null)return "success" ; else return "false"; } }
此時 其實還沒建service 層呢。更別提 service.login()方法了。
所以 新建com.service 包 在com.service包下 新建UserService 接口
UserService 接口代碼
public interface UserService { void login(); }
新建com.service.impl 包 新建com.service.impl.UserServiceImpl 文件 實現UserService接口
代碼如下
public class UserServiceImpl implements UserService { public void login() { System.out.println("這是一個登陸方法"); } }
此時已經完事了。 項目結構圖如下
把項目部署到tomcat 下。 run servers
怎么會404 呢? 那是因為 我並沒有寫index.html
在struts.xml 的配置中 我配置的是 返回 success 的話 去 index.html 頁面
又有這個判斷
if(service!=null)return "success" ;
所以,此時service 注入成功了。
在去看控制台
prefect 完美,這就是ssh項目插件生成,以及配置注解注入service 的全過程