spring aop ---基于AspectJ

因为自己在引用jar包上吃过很多亏,也浪费过很多时间,所以每次都会把使用到的jar包都标明,谢谢理解!

引用jar包:

 

 

1、运行类:

@Service
public class Fit {
    public String say(){
        System.out.println("册数使用的数据!!!!");
//        throw new RuntimeException("失败!!!");
        return "你好啊!!!";
    }
}

 

2、切面类:该类需@Component、@Aspect配合使用,因为classpath路径找不到@Aspect注释的类

@Component
@Aspect
public class MyAspect {
    @Pointcut("execution(* aop.Fit.*(..))")
    public void pointcut(){};
    
    @Before("pointcut()")
    public void before(){
        System.out.println("before....");
    }
    
    @AfterReturning(pointcut = "pointcut()",returning="returnValue")
    public void afterReturnning(Object returnValue){
        System.out.println("afterReturnning....." + returnValue);
    }
    
    @AfterThrowing(pointcut="pointcut()",throwing="e")
    public void afterThrowing(RuntimeException e){
        System.out.println("throwing..." + e.getMessage());
    }
    
    @After("pointcut()")
    public void after(){
        System.out.println("after...");
    }
    
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("11111");
        Object obj = pjp.proceed();
        System.out.println("22222");
        return obj;
    }
}

 

3、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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" 
       xmlns:context="http://www.springframework.org/schema/context" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans  
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-4.0.xsd">
       
       <!-- 开启自动扫描 -->
       <context:component-scan base-package="aop"></context:component-scan>
       <!-- 开启自动代理、织入切面 -->
       <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

 

 

4、测试类:

public class Testa {

    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-aspectj.xml");
        Fit fit = (Fit)context.getBean("fit");
        fit.say();
    }
}

 

 

输出结果:

 

posted @ 2017-05-01 23:59  烈丶凌  阅读(275)  评论(0编辑  收藏  举报