Spring入门---示例五---通过程序代码实现AOP【第二天】

Spring通过程序代码实现AOP示例

一、编写用户DAO类:

 1 package test5.aop.program;
 2 
 3  
 4 
 5 //用户DAO类
 6 
 7 public class UserDao {
 8 
 9 public void addUser(String uname,String upwd){
10 
11 System.out.println("addUser()");
12 
13 }
14 
15 public void deleteUser(String uname) {
16 
17 System.out.println("deleteUser()");
18 
19 }
20 
21 }
22 
23  

 

二、编写检查用户安全的类:

 1 package test5.aop.program;
 2 
 3  
 4 
 5 import org.aspectj.lang.annotation.After;
 6 
 7 import org.aspectj.lang.annotation.Pointcut;
 8 
 9  
10 
11 //检查用户安全的类
12 
13 public class CheckSecurity {
14 
15 /**声明一个切入点 当调用以add以及delete串开始的函数时**/
16 
17 @Pointcut("execution(* add*(..)||execution(* delete*(..)))")
18 
19 private void allAddMethod(){}
20 
21  
22 
23 @After("allAddMethod()")
24 
25 private void check(){
26 
27 System.out.println("check()");
28 
29 }
30 
31 }

 

 

三、改写Spring配置文件:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
 4 
 5     <!-- 以下是设置自动AOP。即通过程序设置AOP -->
 6 
 7         <aop:aspectj-autoproxy/>
 8 
 9         <bean name="check1" class="test5.aop.program.CheckSecurity"/>
10 
11         <bean name="dao1" class="test5.aop.program.UserDao"/>
12 
13 </beans>

 

四、编写测试类:

 1 package test5;
 2 
 3  
 4 
 5 import org.springframework.beans.factory.BeanFactory;
 6 
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 
 9  
10 
11 import test5.aop.program.UserDao;
12 
13  
14 
15 public class Test {
16 
17 @SuppressWarnings("resource")
18 
19 public static void main(String[] args) {
20 
21 BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
22 
23 UserDao dao =(UserDao)factory.getBean("dao1");
24 
25 dao.addUser("zhou", "1234");
26 
27 }
28 
29 }

 

 在编写过程中,配置文件由于没改和本文一致,而是包含前面写的代码,最后出现调用前面写的示例的代码,请思考,

尝试将本文提到的配置加入前面的项目。

posted @ 2019-05-28 16:53  CiscoLee  阅读(232)  评论(0编辑  收藏  举报