使用AspectJ提供的注解方式實現aop


spring實現aop的方式有一下幾種       

        1、基於代理的AOP

        2、純簡單java對象切面

        3、@Aspect注解形式的

        4、注入形式的Aspcet切面

下面是用@aspect注解形式實現的,首先是導入一些的jar包

切面的代碼

@Component
@Aspect
public class Advice {
    @Before("init()")//通知
    public void log(){
        System.out.println("before do...");
    }
    
    @Pointcut("execution(* service.*.*(..))")//方法切入點,execution為執行的意思,*代表任意返回值,然后是包名,.*意思是包下面的所有子包。(..)代表各種方法.
public void init(){
        
    }
}

實現類

@Component("serviceImpl")
public class ServiceImpl implements Service {

    @Override
    public void saySomething() {

        System.out.println("do..");
        
    }
}

spring的配置文件中添加

    <context:annotation-config></context:annotation-config>
    <context:component-scan base-package="service,advice"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

通過aop命名空間的<aop:aspectj-autoproxy />聲明自動為spring容器中那些配置@aspectJ切面的bean創建代理,織入切面。當然,spring

在內部依舊采用AnnotationAwareAspectJAutoProxyCreator進行自動代理的創建工作,但具體實現的細節已經被<aop:aspectj-autoproxy />隱藏起來了

測試代碼 

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext ac = new ClassPathXmlApplicationContext("service/bean.xml");
        Service ser =  (Service) ac.getBean("serviceImpl");
        ser.saySomething();
    }

}

結果就是在輸出do..之前輸出了before do...

實際應用中可以用來實現日志功能


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM