java AOP使用注解@annotation方式實踐


AOP實際開發工作比較常用,在此使用注解方式加深對面向切面編程的理解

廢話不多少,先看下面的實例代碼

場景:

1.未滿一歲的小孩,在執行方法之前打印:“還沒有滿一歲,不會說話”,在執行方法之后打印:“請多多關注我!”

2.大於一歲的小孩,在執行方法之前打印:“大家好,我的名字叫: "+ baby.getName() + "我今年 "+ baby.getAge() +" 歲了!”,在執行方法之后打印:“請多多關注我!”

切面類:定義切點和切面方法

@Aspect
@Component
public class CheckAgeAspect {

    @Autowired
    Baby baby;

    @Pointcut("@annotation(com.mb.util.CheckAge)")  //@annotation聲明以注解的方式來定義切點
    public void checkDataPoint(){

    }
    @Before("checkDataPoint()")  //前置通知
    public void checkBefore(){
        if (baby.getAge() <= 1) {
            System.out.println("還沒有滿一歲,不會說話");
        }else {
            System.out.println("大家好,我的名字叫: "+  baby.getName() + "我今年 "+ baby.getAge() +" 歲了!");
        }
    }
    @After("checkDataPoint()") //后置通知
    public void checkAfter(){
        System.out.println("請多多關注我!");
    }
}

/**
after returning 目標方法返回時執行 ,后置返回通知
after throwing 目標方法拋出異常時執行 異常通知
around 在目標函數執行中執行,可控制目標函數是否執行,環繞通知
以上三種通知使用上基本雷同不舉例了
**/

注解方法:使用注解的方式來定義,在目標方法上面標注該注解

@Target(ElementType.METHOD)   //定義注解的使用范圍為方法
@Retention(RetentionPolicy.RUNTIME )
public @interface CheckAge {

}

目標類

@Data  //需要導入import lombok.Data; 通過注解搞定getter和setter
@Component
public class Baby {

    private int age;
    private String name;

    @CheckAge
    public void say(){
        System.out.println("執行目標方法");
    }
}

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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="com.mb"></context:component-scan>   <!--項目包掃描-->
<aop:aspectj-autoproxy proxy-target-class="false"></aop:aspectj-autoproxy> <!--使用注解的方式,需要添加該標簽,它會調用AspectJAutoProxyBeanDefinitionParser的parse來解析;   proxy-target-class為true則是基於類的代理將起作用(需要cglib庫),為false或者省略這個屬性,則標准的JDK 基於接口的代理將起作用,一般采用后者,因為前者效率高-->
</beans>

測試類:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/applicationContext*.xml"})
public class DemoTest {

@Autowired
Baby person;
@Test
public void demoTest(){
person.setAge(3);
person.setName("美美");
person.say();
}
}

執行結果:

大家好,我的名字叫: 美美我今年 3 歲了!
執行目標方法
請多多關注我!

 


免責聲明!

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



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