注解?
1-导入spring-aop包和aspectjweaver包
2-创建Teacher接口和实现类:添加注解@Repository(“id”)
package p313.aop.annotation;public interface Teacher {//上课教书public void teach();}
package p313.aop.annotation;import org.springframework.stereotype.Repository;@Repository(\"teacher\")public class TeacherImpl implements Teacher {@Overridepublic void teach() {System.out.println(\"老师上课进行中\");}}
3-创建切面类:添加注解@Aspect @Component和定义前置后置增前和切点
package p313.aop.annotation;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.aspectj.lang.annotation.Pointcut;import org.springframework.stereotype.Component;@Aspect@Componentpublic class MyAspect {//定义一个方法:要求返回类型为void,方法体为空,参数列表为空@Pointcut(\"execution(* p313.aop.annotation.*.*(..))\")public void myPointCut(){}//需要代理的方法:点名@Before(\"myPointCut()\")public void callName(){System.out.println(\"点名\");}//收发作业@After(\"myPointCut()\")public void collectHomework(){System.out.println(\"收发作业\");}}
4-在配置文件中配置
<!--扫描包,是注解生效--><context:component-scan base-package=\"p313.aop.annotation\"/><!--开启aspectj的支持--><aop:aspectj-autoproxy/>
5-测试
@Testpublic void test1(){//获得配置文件ApplicationContext applicationContext =new ClassPathXmlApplicationContext(\"p313/aop/annotation/applicationContext.xml\");//获得teacher对象Teacher teacher= (Teacher) applicationContext.getBean(\"teacher\");//调用教书方法teacher.teach();}