程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> struts2.3.24+spring4.1.6+hibernate4.3.11+mysql5.5.25開辟情況搭建圖文教程

struts2.3.24+spring4.1.6+hibernate4.3.11+mysql5.5.25開辟情況搭建圖文教程

編輯:關於JAVA

struts2.3.24+spring4.1.6+hibernate4.3.11+mysql5.5.25開辟情況搭建圖文教程。本站提示廣大學習愛好者:(struts2.3.24+spring4.1.6+hibernate4.3.11+mysql5.5.25開辟情況搭建圖文教程)文章只能為提供參考,不一定能成為您想要的結果。以下是struts2.3.24+spring4.1.6+hibernate4.3.11+mysql5.5.25開辟情況搭建圖文教程正文


struts2.3.24 + spring4.1.6 + hibernate4.3.11+ mysql5.5.25開辟情況搭建及相干解釋。

1、目的

1、搭建傳統的ssh開辟情況,並勝利運轉(拔出、查詢)

2、懂得c3p0銜接池相干設置裝備擺設

3、懂得驗證hibernate的二級緩存,並驗證

4、懂得spring事物設置裝備擺設,並驗證

5、懂得spring的IOC(依附注入),將struts2的action對象(bean)交給spring治理,自界說bean等...並驗證

6、懂得spring aop(面向切面編程),並編寫自界說切面函數,驗證成果

2、後期預備

開辟情況:eclipse for java ee;mysql5.5.25;jdk1.7.0_79;navicat10.1.7(可選);

創立數據庫demo:

/*
Navicat MySQL Data Transfer

Source Server : localhost_3306
Source Server Version : 50519
Source Host : localhost:3306
Source Database : demo

Target Server Type : MYSQL
Target Server Version : 50519
File Encoding : 65001

Date: 2016-01-09 23:36:02
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,
 `account` varchar(200) NOT NULL,
 `name` varchar(200) NOT NULL,
 `address` varchar(1000) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

新建web工程,目次構造以下:

jar包預備,放到WEB-INF的lib目次下(有興致的可以用maven治理進程,然則有時刻下載jar包很慢...)

相干jar包都可以鄙人載上去的struts、spring、hibernate中找到,這裡給個參考,有些是可以刪除的,好比spring mvc部門的jar包:

3、設置裝備擺設web.xml

設置裝備擺設一個struts2的filter,映照一切*.action要求,由StrutsPrepareAndExecuteFilter對象來處置;

設置裝備擺設context-param參數,指定spring設置裝備擺設文件的途徑,<context-param>中的參數可以用ServletContext.getInitParameter(“param-name”)來獲得;

設置裝備擺設listener,重要是讀取applicationContext.xml設置裝備擺設文件信息,創立bean等初始化任務;

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <display-name>SSH</display-name>

 <filter>
 <filter-name>struts2</filter-name>
 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>

 <filter-mapping>
 <filter-name>struts2</filter-name>
 <url-pattern>*.action</url-pattern>
 </filter-mapping>

 <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>

 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

</web-app>

4、設置裝備擺設applicationContext.xml

設置裝備擺設主動掃描ssh包下的@Repostory,@Service等注解,並生成對應的bean;

設置裝備擺設數據源(jdbc銜接池為c3p0,可以參考c3p0的具體設置裝備擺設),銜接池重要感化是疾速供給connection,反復應用,不須要每次燒毀創立,需設置裝備擺設用戶名、暗碼、最年夜銜接數、最小銜接數、初始銜接數等相干參數;

設置裝備擺設sessionFactory(可以參考hibernate的具體設置裝備擺設,這裡設置裝備擺設開啟二級緩存),重要感化是供給session,履行sql語句;這裡我們將會經由過程HibernateTemplate來對數據庫停止操作,便利spring停止什物掌握;ps,hibernate設置裝備擺設中還要設置裝備擺設類與數據庫表的映照;

設置裝備擺設事務治理器bean為HibernateTransactionManager,並把成員屬性sessionFactory初始化為之前設置裝備擺設的sessionFactory bean;

設置裝備擺設事務的流傳特征,並設置裝備擺設一個切面援用它,對一切ssh.service包及子包下一切add、delete、update、save辦法停止事務掌握,還可以設置裝備擺設事務流傳行動等參數;

最初是一個自界說aop相干設置裝備擺設,對ssh.aop.AopTest下一切test開首的辦法運用自界說切面‘myAop'停止掌握,後續會驗證成果;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
 http://www.springframework.org/schema/jdbc
 http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.1.xsd">
 
 <!-- scans the classpath for annotated components (including @Repostory 
 and @Service that will be auto-registered as Spring beans --> 
 <context:component-scan base-package="ssh" />

 <!--配數據源 -->
 <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
 <property name="driverClass" value="com.mysql.jdbc.Driver" />
 <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo" />
 <property name="user" value="root" />
 <property name="password" value="root" />
 
 <property name="acquireIncrement" value="1"></property> 
 <property name="initialPoolSize" value="80"></property> 
 <property name="maxIdleTime" value="60"></property> 
 <property name="maxPoolSize" value="80"></property> 
 <property name="minPoolSize" value="30"></property> 
 <property name="acquireRetryDelay" value="1000"></property> 
 <property name="acquireRetryAttempts" value="60"></property> 
 <property name="breakAfterAcquireFailure" value="false"></property>
 <!-- 如湧現Too many connections, 留意修正mysql的設置裝備擺設文件my.ini,增年夜最多銜接數設置裝備擺設項,(檢查以後銜接敕令:show processlist) -->
 </bean>
 
 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
 <property name="dataSource" ref="dataSource" />

 <property name="hibernateProperties">
 <props>
 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
 <prop key="hibernate.show_sql">true</prop>
 <prop key="hibernate.hbm2ddl.auto">update</prop>
 <prop key="current_session_context_class">thread</prop>
 <prop key="hibernate.cache.use_second_level_cache">true</prop>
 <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
 <prop key="hibernate.cache.use_query_cache">true</prop>
 <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
 </props>
 </property>
 <property name="mappingLocations"> 
 <list> 
 <value>classpath:ssh/model/User.hbm.xml</value> 
 </list> 
 </property> 
 <!-- 
 <property name="annotatedClasses">
 <list>
 <value>ssh.model.User</value>
 </list>
 </property>
 -->
 </bean>
 
 <!-- 設置裝備擺設事務治理器 -->
 <bean id="transactionManager"
 class="org.springframework.orm.hibernate4.HibernateTransactionManager">
 <property name="sessionFactory" ref="sessionFactory" />
 </bean>
 
 <!-- 事務的流傳特征 -->
 <tx:advice id="txadvice" transaction-manager="transactionManager">
 <tx:attributes>
 <tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
 <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
 <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
 <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/>
 </tx:attributes>
 </tx:advice>
 

 <aop:config>
 <aop:pointcut id="pcMethod" expression="execution(* ssh.service..*.*(..))" />
 <aop:advisor pointcut-ref="pcMethod" advice-ref="txadvice" />
 </aop:config>
 
 <!-- 自界說aop處置 測試 -->
 <bean id="aopTest" class="ssh.aop.AopTest"></bean>
 <bean id="myAop" class="ssh.aop.MyAop"></bean>
 <aop:config proxy-target-class="true">
 <aop:aspect ref="myAop">
 <aop:pointcut id="pcMethodTest" expression="execution(* ssh.aop.AopTest.test*(..))"/>
 <aop:before pointcut-ref="pcMethodTest" method="before"/>
 <aop:after pointcut-ref="pcMethodTest" method="after"/>
 </aop:aspect>
 </aop:config>

 </beans>

5、設置裝備擺設struts.xml

設置裝備擺設struts.objectFactory常數為spring,表現action由經由過程spring的bean中獲得;

設置裝備擺設result type為"json",也能夠設置裝備擺設其它的,這裡為了前後端數據交互輕便,設置裝備擺設成json格局;

設置裝備擺設兩個action,addUser和queryAllUser;

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
 <constant name="struts.objectFactory" value="spring"/>
 <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 <constant name="struts.devMode" value="false" />

 <package name="default" extends="struts-default,json-default">


 <global-results>
 <result type="json">
 <param name="root">json</param>
 <param name="contentType">text/html</param>
 </result>
 </global-results> 

 <action name="addUser" class="userAction" method="addUser">
 <result>.</result>
 </action>
 
 <action name="queryAllUser" class="userAction" method="queryAllUser">
 <result>.</result>
 </action>
 
 </package>


 <!-- Add packages here -->

</struts>

6、編寫相干代碼

留意事項:

dao繼續HibernateDaoSupport類,一切數據庫相干操感化hibernateTemplate操作;

給dao層,service層,action添加響應注解,注冊為spring的bean;

附代碼以下:

UserAction.java

package ssh.action;

import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import ssh.aop.AopTest;
import ssh.model.User;
import ssh.service.UserService;

import com.谷歌.gson.Gson;

@Controller
public class UserAction {
 Logger logger = Logger.getLogger(UserAction.class);
 @Resource
 private UserService userService;
 @Resource
 private AopTest aopTest;
 
 public void addUser(){
 PrintWriter out = null;
 

 
 try{
 HttpServletRequest request = ServletActionContext.getRequest();
 HttpServletResponse response = ServletActionContext.getResponse();
 response.setContentType("text/html;charset=UTF-8");
 String account = request.getParameter("account");
 String name = request.getParameter("name");
 String address = request.getParameter("address"); 
 User user = new User();
 user.setAccount(account);
 user.setAddress(address);
 user.setName(name);
 userService.add(user);
 out = response.getWriter();
 out.write(new Gson().toJson("success"));
 }catch(Exception e){
 e.printStackTrace();
 logger.error(e.getMessage());
 if(out != null)
 out.write(new Gson().toJson("fail"));
 }finally{
 out.flush();
 out.close();
 }
 
 }
 
 
 public void queryAllUser(){
 PrintWriter out = null;
 
 aopTest.test1();
 aopTest.test2();
 //logger.error("i");
 try {
 HttpServletResponse response = ServletActionContext.getResponse();
 response.setContentType("text/html;charset=UTF-8");
 
 Gson gson = new Gson();
 List<User> userList= userService.queryAllUser();
 String gsonStr = gson.toJson(userList);
 
 out = response.getWriter();
 out.write(gsonStr);
 } catch (Exception e) {
 e.printStackTrace();
 logger.error(e.getMessage());
 if(out != null)
 out.write(new Gson().toJson("fail"));
 }finally{
 out.flush();
 out.close();
 }
 }
}

AopTest.java

package ssh.aop;



public class AopTest {

 
 public void test1(){
 System.out.println("AopTest test1 method is running~");
 }
 
 public void test2(){
 System.out.println("AopTest test2 method is running~");
 }
}

MyAop.java

package ssh.aop;


public class MyAop {

 public void before(){
 System.out.println("befor~");
 }
 
 public void after(){
 System.out.println("after~");
 }
}

BaseDao.java

package ssh.dao.base;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;


public class BaseDao extends HibernateDaoSupport{
 @Resource 
 public void setMySessionFactory(SessionFactory sessionFactory){ 
 this.setSessionFactory(sessionFactory); 
 }
}

UserDao.java

package ssh.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import ssh.dao.base.BaseDao;
import ssh.model.User;

@Repository
public class UserDao extends BaseDao{
 public void add(User user){
 this.getHibernateTemplate().save(user);
 }
 
 @SuppressWarnings("unchecked")
 public List<User> queryAllUser(){
 
 List<User> users = new ArrayList<User>();
 HibernateTemplate hibernateTemplate = this.getHibernateTemplate();
 
 hibernateTemplate.setCacheQueries(true);
 users = (List<User>) hibernateTemplate.find("from User");
 hibernateTemplate.setCacheQueries(false);

 return users;
 }

}

User.java

package ssh.model;

import java.io.Serializable;



public class User implements Serializable{

 /**
 * 
 */
 private static final long serialVersionUID = -6190571611246371934L;
 private Long id;
 private String account;
 private String name;
 private String address;
 public String getAccount() {
 return account;
 }
 public String getName() {
 return name;
 }
 public String getAddress() {
 return address;
 }
 public void setAccount(String account) {
 this.account = account;
 }
 public void setName(String name) {
 this.name = name;
 }
 public void setAddress(String address) {
 this.address = address;
 }
 /**
 * @return the id
 */
 public Long getId() {
 return id;
 }
 /**
 * @param id the id to set
 */
 public void setId(Long id) {
 this.id = id;
 }
}

User.hbm.xml

<?xml version="1.0"?>

<!--
 ~ Hibernate, Relational Persistence for Idiomatic Java
 ~
 ~ Copyright (c) 2010, Red Hat Inc. or third-party contributors as
 ~ indicated by the @author tags or express copyright attribution
 ~ statements applied by the authors. All third-party contributions are
 ~ distributed under license by Red Hat Inc.
 ~
 ~ This copyrighted material is made available to anyone wishing to use, modify,
 ~ copy, or redistribute it subject to the terms and conditions of the GNU
 ~ Lesser General Public License, as published by the Free Software Foundation.
 ~
 ~ This program is distributed in the hope that it will be useful,
 ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 ~ for more details.
 ~
 ~ You should have received a copy of the GNU Lesser General Public License
 ~ along with this distribution; if not, write to:
 ~ Free Software Foundation, Inc.
 ~ 51 Franklin Street, Fifth Floor
 ~ Boston, MA 02110-1301 USA
 -->

<!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="ssh.model">

 <class name="User" table="user">
 <cache usage="read-write"/>
 <id name="id" column="id">
 <generator class="increment"/>
 </id>
 <property name="account" type="java.lang.String" column="account"/>
 <property name="name" type="java.lang.String" column="name"/>
 <property name="address" type="java.lang.String" column="address"/>
 </class>

</hibernate-mapping>

UserService.java

package ssh.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import ssh.dao.UserDao;
import ssh.model.User;


@Service
public class UserService {
 @Resource
 private UserDao userDao = new UserDao();
 public List<User> queryAllUser(){
 return userDao.queryAllUser();
 
 }
 public void add(User user){
 userDao.add(user);
 }
}

index.jsp(記得添加jquery庫)

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
.mt20{
 margin-top: 20px;
}
</style>
</head>
<body>

<div >
 <div class="mt20"><label>賬號:</label><input id="account" type="text"/></div>
 <div class="mt20"><label>姓名:</label><input id="name" type="text"/></div>
 <div class="mt20"><label>地址:</label><input id="address" type="text"/></div>
 <div class="mt20"><button id="addUser" >添加</button></div>
</div>

<h3>用戶列表:</h3>
<ul id="userList">
</ul>

<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>

<script>
 $(function() {
 $.ajax({
 url : 'queryAllUser.action',
 type : 'post',
 dataType : 'json',
 success : function(data) {
 try {
 for(var i = 0; i < data.length; i++){
 $("#userList").append("<li><span style='color:red'>id="+data[i].id+"</span>,account="+data[i].account+",name="+data[i].name+",address="+data[i].address+"</li>");
 }
 } catch (e) {};
 
 }
 ,
 error : function(e) {
 alert("sys error");
 }
 });
 
 $("#addUser").on("click", function() {
 var account = $("#account").val();
 var name = $("#name").val();
 var address = $("#address").val();
 $.ajax({
 url : 'addUser.action',
 type : 'post',
 dataType : 'json',
 data : {
 account : account,
 name : name,
 address : address
 },
 success : function(data) {
 try {
 
 $("#userList").append("<li>account="+account+",name="+name+",address="+address+"</li>");
 alert("添加勝利");
 } catch (e) {

 }
 },
 error : function(e) {
 alert("sys error");
 }
 });

 });
 });
</script>
</body>
</html>

7、驗證成果

回到開首,開端熟習懂得相干技巧,並驗證成果

1、搭建傳統的ssh開辟情況,並勝利運轉(拔出、查詢)

以下圖:查詢及添加用戶勝利;

2、懂得c3p0銜接池相干設置裝備擺設

數據庫銜接是一種昂貴的資本,開啟及封閉比擬消費機能,是以可以用銜接池來治理,初始化若干個銜接,反復應用,而不是反復創立封閉,有點相似線程池;

設置裝備擺設以下,要依據現實項目情形公道設置裝備擺設最小最年夜銜接數,具體的各個參數寄義可以參考鏈接

別的要驗證銜接數相干設置裝備擺設很簡略,可以本身寫個法式驗證,好比當設置裝備擺設最年夜銜接數為10的時刻,可以寫個法式驗證,當翻開10個connection後,第11個connection會一向處於期待狀況,獲得不到;所以要依據情形公道設置裝備擺設銜接數,不然有能夠會影呼應用機能;

<!--配數據源 -->
 <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
 <property name="driverClass" value="com.mysql.jdbc.Driver" />
 <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo" />
 <property name="user" value="root" />
 <property name="password" value="root" />
 
 <property name="acquireIncrement" value="1"></property> 
 <property name="initialPoolSize" value="80"></property> 
 <property name="maxIdleTime" value="60"></property> 
 <property name="maxPoolSize" value="80"></property> 
 <property name="minPoolSize" value="30"></property> 
 <property name="acquireRetryDelay" value="1000"></property> 
 <property name="acquireRetryAttempts" value="60"></property> 
 <property name="breakAfterAcquireFailure" value="false"></property>
 <!-- 如湧現Too many connections, 留意修正mysql的設置裝備擺設文件my.ini,增年夜最多銜接數設置裝備擺設項,(檢查以後銜接敕令:show processlist) -->
 </bean>

3、懂得驗證hibernate的二級緩存,並驗證

hibernate的一級緩存是指session規模的緩存,默許開啟,二級緩存是sessionFactory規模緩存,在設置裝備擺設sessionFactory的時刻,我們曾經設置裝備擺設二級緩存為ehcache,接上去驗證後果,查詢user操作,發明第一次查詢會操作數據庫,打印sql語句,刷新頁面後,發明查詢勝利且沒打印sql語句,以下圖,可見二級緩存任務OK;

4、懂得spring事物設置裝備擺設,並驗證

所謂事務掌握,道理都一樣,就是要包管原子性、分歧性、隔離性、耐久性,jdbc編程的時刻,都是本身掌握,經由過程set autocommit=false設置成不主動提交,然後開端寫詳細的數據庫操作,產生異常的時刻rollback,不然commit;其實spring對事物的掌握道理也差不多,加了一些封裝,設置裝備擺設等,加倍便利罷了,好比可以在service層分歧辦法停止掌握等;

驗證的話很簡略,在service層某個辦法(留意辦法名要相符spring設置裝備擺設文件中設置裝備擺設的規矩)內寫兩個拔出user的操作,在中央拋出一個異常,然後履行,假如發明第一個user拔出勝利,解釋事務掌握掉效,不然ok;

5、懂得spring的IOC(依附注入),將struts2的action對象(bean)交給spring治理,自界說bean等...並驗證

細心不雅察的話,在設置裝備擺設applicationContext.xml文件的進程中,重要任務都是在設置裝備擺設bean相干信息,這些bean都是事前創立好的,其實所謂的bean就是對象;

之所以把對象的創立交給spring容器,目標是為懂得耦;

別的在用struts的時刻,spring把action注冊為bean,默許是單例的,拜訪的時刻其實不是每次都new出一個action,在並發拜訪的時刻,會有風險;

不外,可以經由過程scope="prototype",把action設置裝備擺設成多例;ps:struts2中的action默許是多例;

留意:applicationContext.xml設置裝備擺設的bean和自界說注解的bean都是可以在法式運轉的進程中直接獲得的,經由過程@Resource等方法,這個很好驗證,寫個小法式便可;

6、懂得spring aop(面向切面編程),並編寫自界說切面函數,驗證成果

切面編程這類情勢許多處所都用了該思惟,甚麼過濾器,攔阻器,事務掌握等等...

其道理照樣java的反射和靜態署理,在辦法履行前後加以掌握,參加本身要履行的代碼;

小例子中加了個切面,在辦法履行前後打印before和after字符串,以下圖,任務正常,代碼參考後面部門:

<!-- 自界說aop處置 測試 -->
 <bean id="aopTest" class="ssh.aop.AopTest"></bean>
 <bean id="myAop" class="ssh.aop.MyAop"></bean>
 <aop:config proxy-target-class="true">
 <aop:aspect ref="myAop">
 <aop:pointcut id="pcMethodTest" expression="execution(* ssh.aop.AopTest.test*(..))"/>
 <aop:before pointcut-ref="pcMethodTest" method="before"/>
 <aop:after pointcut-ref="pcMethodTest" method="after"/>
 </aop:aspect>
 </aop:config>

@author   風一樣的碼農

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved