struts2.3.24 + spring4.1.6 + hibernate4.3.11+ mysql5.5.25開發環境搭建及相關說明。
一、目標
1、搭建傳統的ssh開發環境,并成功運行(插入、查詢)
2、了解c3p0連接池相關配置
3、了解驗證hibernate的二級緩存,并驗證
4、了解spring事物配置,并驗證
5、了解spring的IOC(依賴注入),將struts2的action對象(bean)交給spring管理,自定義bean等...并驗證
6、了解spring aop(面向切面編程),并編寫自定義切面函數,驗證結果
二、前期準備
開發環境:eclipse for java ee;mysql5.5.25;jdk1.7.0_79;navicat10.1.7(可選);
創建數據庫demo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
/* 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包:
三、配置web.xml
配置一個struts2的filter,映射所有*.action請求,由StrutsPrepareAndExecuteFilter對象來處理;
配置context-param參數,指定spring配置文件的路徑,<context-param>中的參數可以用ServletContext.getInitParameter(“param-name”)來獲取;
配置listener,主要是讀取applicationContext.xml配置文件信息,創建bean等初始化工作;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<? 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 > |
四、配置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'進行控制,后續會驗證結果;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
<? 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 > |
五、配置struts.xml
配置struts.objectFactory常數為spring,表示action由通過spring的bean中獲取;
配置result type為"json",也可以配置其它的,這里為了前后端數據交互簡便,配置成json格式;
配置兩個action,addUser和queryAllUser;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<? 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 > |
六、編寫相關代碼
注意事項:
dao繼承HibernateDaoSupport類,所有數據庫相關操作用hibernateTemplate操作;
給dao層,service層,action添加相應注解,注冊為spring的bean;
附代碼如下:
UserAction.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
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.google.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package ssh.aop; public class MyAop { public void before(){ System.out.println( "befor~" ); } public void after(){ System.out.println( "after~" ); } } |
BaseDao.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<? 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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庫)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
<%@ 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 style = "text-align: center;" > < 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 > |
七、驗證結果
回到開頭,開始熟悉了解相關技術,并驗證結果
1、搭建傳統的ssh開發環境,并成功運行(插入、查詢)
如下圖:查詢及添加用戶成功;
2、了解c3p0連接池相關配置
數據庫連接是一種昂貴的資源,開啟及關閉比較消耗性能,因此可以用連接池來管理,初始化若干個連接,重復使用,而不是重復創建關閉,有點類似線程池;
配置如下,要根據實際項目情況合理配置最小最大連接數,詳細的各個參數含義可以參考鏈接
另外要驗證連接數相關配置很簡單,可以自己寫個程序驗證,比如當配置最大連接數為10的時候,可以寫個程序驗證,當打開10個connection后,第11個connection會一直處于等待狀態,獲取不到;所以要根據情況合理配置連接數,否則有可能會影響應用性能;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!--配數據源 --> <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字符串,如下圖,工作正常,代碼參考前面部分:
1
2
3
4
5
6
7
8
9
10
|
<!-- 自定義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 風一樣的碼農
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/chenpi/p/5153593.html