您的位置:首页 > 编程语言 > ASP

学习笔记之springAOP的aspectJ实现注意点总结

2017-06-04 15:34 746 查看
在使用spectj注解实现springAOP:

1.需要使用@Aspect注解来标注切面

2.可以使用@before,@afterRuning,@around,@afterThrowning注解,来标注通知

3.必须有切入点point-cut,使用@pointcut(execution(""))注解来标注切入点

4.在aop.xml中,需要有

<aop:aspectj-autoproxy />,制定开启aspectj自动代理
5.在spring的动态代理底层使用的是jdk的代理机制,
newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) 第一个参数是需要代理的类,第二个参数是需要代理类实现的接口,所以称为接口代理,
必须有指定接口。
package com.kayak;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect//切面类
public class Sleep {

@Before("sleePpoint()")
public void beforeSleep(){
System.out.println("睡觉之前要记得脱衣服");
}
@Pointcut("execution(* com.kayak.*.sleep(..))")
public void sleePpoint(){
System.out.println("...............");
}
@AfterReturning("sleePpoint()")
public void afterSleep(){
System.out.println("睡醒之后要记得穿衣服");
}

}





测试类

package com.kayak;

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

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-aop.xml");
TimeHandleable sleep = (TimeHandleable)ctx.getBean("timeHandle");
sleep.sleep();
}

}



接口,接口必须要有,如果不使用接口代码的方式,spring也支持CGLB代理,只需要导入asm的jar包,在xml中设置
<aop:aspectj-autoproxy proxy-target-class="true"/>就可以


package com.kayak;

public interface TimeHandleable {

public void sleep();
}
实现类
package com.kayak;

public class TimeHandle implements TimeHandleable{

public void sleep(){
System.out.println("12点钟之前一定要睡觉");
}
}


aop.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> <bean id="sleep" class="com.kayak.Sleep"></bean>
<bean id ="timeHandle" class="com.kayak.TimeHandle"></bean>
<aop:aspectj-autoproxy />
</beans>



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: