SpringAop的注解形式

来源:互联网 发布:linux ntp客户端 编辑:程序博客网 时间:2024/05/18 23:56
1.applicationContext.xml文件:


<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

<!-- 开启自动注解,自动代理1.切面  2.切点expression=""-->
<aop:aspectj-autoproxy/>

<!-- 实例化 -->
<bean name="userinfoService" class="test.UserinfoService"></bean>
<bean name="userinfoProxy" class="test.UserinfoProxy"></bean>




</beans>
----------------------------------------------------------
2.UserinfoService.java:


package test;


public class UserinfoService {

// 一个添加方法
public void save(){
System.out.println("这是一个ORM框架做的添加方法 ");
}

//一个修改方法
public void update(){
System.out.println("这是一个ORM框架做的修改方法 ");
}
}
---------------------------------------------------------------
UserinfoProxy.java:


package test;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;


//切面aspect
@Aspect
public class UserinfoProxy {
//通知=方法
//before通知
// @Before("execution(* test.UserinfoService.save(..))")
// public void before(){
// System.out.println("我会在调用方法前");
// }

//after通知
// @After("execution(* test.UserinfoService.save(..))")
// public void after(){
// System.out.println("我会在调用方法后");
// }

//环绕通知
@Around("execution(* test.UserinfoService.*(..))")
public Object around(ProceedingJoinPoint point){
if(point.getSignature().getName().equals("save")){//放行
try {
return point.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
}
return null;//阻止

}
-----------------------------------------------------------------
3.测试文件:Test.java:


package test;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Test {


public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserinfoService service = (UserinfoService) ctx.getBean("userinfoService");
//service.save();
service.update();
}


}
0 0
原创粉丝点击