Spring Aop 实例
springAOP 封装了JDK和cglib AOP分两类 :一类以方法的参数进行拦截 ,一类:是对方法拦截 springAOP 属于方法级的 springAOP 实现方式 1.基于@AspectJ注解方式 2.基于xml配置的方式 基于注解实现 定义核心业务逻辑接口 public interface eatMan { void eat(); } 定义核心业务逻辑接口实现 @Service //@Component public class human implements eatMan { @Override public void eat() { // int b=0; // int a=2/b; System.out.println("吃。。。。。。。。。。。。"); } @Override public String haha() { return "赵"; } } 自定义springAop注解 //注入到容器中 @Component //切面注解 @Aspect public class notify { public notify() { } //写了一个通用的拦截切面 @Pointcut("execution(* *.eat(..))") public void eatNotify() { } @Before("eatNotify()") public void before(){ System.out.println("before...."); } @After("eatNotify()") public void after(){ System.out.println("after...."); } @AfterThrowing(value = "eatNotify()",throwing = "e") public void exception(Throwable e){ System.out.println("eat()方法异常信息为"+e); } @AfterReturning(value ="execution(* *.haha(..))",returning = "re") public void returns(String re) throws Throwable { System.out.println("名字:"+re); } // 定义环绕通知方法 // 方法必须接受 ProceedingJoinPoint 为参数,因为要通过它来调用被通知的方法。 // 我们可以在方法中执行其他操作。当需要执行被通知的方法时 // 就调用 ProceedingJoinPoint 的 proceed()。 // @Around("eatNotify()") // public void aroud(ProceedingJoinPoint p) { // { // System.out.println("before...."); // 相当于@Before
// // try { // p.proceed();// 通过调用此方法来执行被通知的方法 // System.out.println("after......"); // 相当于@After // } catch (Throwable throwable) { // throwable.printStackTrace();//相当于@AfterThrowing // } // } // } } 配置aop扫描,基于注解,也可以用xml的形式 @Configuration @EnableAspectJAutoProxy @ComponentScan("com.lala.zhao.aop.test") public class config { } //@ContextConfiguration(classes = config.class) public class testMain { private static ApplicationContext ctx; // @Autowired // eatMan eat; @Test public void mai (){ ctx=new AnnotationConfigApplicationContext(config.class); eatMan eat= (eatMan) ctx.getBean(eatMan.class); eat.eat(); eat.haha(); } }


浙公网安备 33010602011771号