Spring AOP:@Before、@After 的 JavaConfig 寫法


網絡上關於Spring AOP的范例大都是使用xml作配置文件,見此特地寫一些JavaConfig的范例,既為加深理解,亦為加強記憶。如需引用或轉載的同學,請注明來源。

使用Spring AOP,要成功運行起代碼,只用Spring提供給開發者的jar包是不夠的,請額外上網下載兩個jar包導入項目中:

  • aopalliance.jar
  • aspectjweaver.jar。

由於我使用IDEA_U創建的spring項目,aopalliance.jar是Maven自動下載的,而 aspectjweaver.jar 則需要另外下載aspectj.jar,然后用解壓軟件打開,解壓出 aspectjweaver.jar

 

先寫一個接口:

@Component
public interface Person {
    void say();
    void run();
}

 

再寫兩個實現類:

@Component
@Qualifier("adults")
public class Adults implements Person {

    private String classname = "adults";

    @Override
    public void say() {
        System.out.println("I am " + classname + " , I like acid rock.");
    }

    @Override
    public void run() {
        System.out.println("I am " + classname + " , I like long-distance");
    }
}
@Component
@Qualifier("children")
public class Children implements Person {

    private String classname = "children";

    @Override
    public void say() {
        System.out.println("We are " + classname + " , we like nursery rhymes.");
    }

    @Override
    public void run() {
        System.out.println("We are " + classname + " , we like running around.");
    }
}

 

然后寫一個切面,這也是一個類:

@Component
@Aspect //聲明這是一個切面。必須的!
public class AspectConfig {

    //通知和切入點的混合寫法;
    //第一個 * 號表示任意返回類型,第二個 * 號表示Person的所有方法
    @Before("execution(* com.san.spring.aop.Person.*(..))")
    public void showTime1(){
        System.out.println("CurrentTime = " + System.currentTimeMillis());
    }

    @After("execution(* com.san.spring.aop.Person.*(..))")
    public void showTime2(){
        System.out.println("CurrentTime = " + System.currentTimeMillis());
    }
}

上面的切面也可以這樣定義

@Component
@Aspect //聲明這是一個切面。必須的! 
public class AspectConfig {

    // 定義一個切點
    @Pointcut("execution(* com.san.spring.aop.Person.*(..))")
    public void pointcut(){}

    // 定義通知
    @Before("pointcut()")
    public void showTime1(){
        System.out.println("CurrentTime = " + System.currentTimeMillis());
    }

    // 定義通知
    @After("pointcut()")
    public void showTime2(){
        System.out.println("CurrentTime = " + System.currentTimeMillis());
    }
}

 

定義spring的JavaConfig類:

@Configuration
@ComponentScan
@EnableAspectJAutoProxy //啟用自動代理功能。必須的!
public class SpringConfig {
}

 

寫一個測試類:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class AopTest {

    @Autowired
    @Qualifier("children")
    private Person person;

    @Test
    public void testMethod(){
        person.say();
        person.run();
    }
}

 

本文參考了http://www.cnblogs.com/xrq730/p/4919025.html


免責聲明!

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



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