Spring AOP之Introduction(@DeclareParents)簡介


  Spring的文檔上對Introduction這個概念和相關的注解@DeclareParents作了如下介紹:
  Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare that advised objects implement a given interface, and to provide an implementation of that interface on behalf of those objects.
An introduction is made using the @DeclareParents annotation. This annotation is used to declare that matching types have a new parent (hence the name).
 
  在這段介紹之后還給出了一個例子,對於初學者要理解這段話以及后面的例子還是蠻困難的,因此下面用一個簡單的例子告訴大家什么是Introduction以及如何使用@DeclareParents注解。
  對於Introduction這個詞,個人認為理解成引入是最合適的,其目標是對於一個已有的類引入新的接口(有人可能會問:有什么用呢?簡單的說,你可以把當前對象轉型成另一個對象,那么很顯然,你就可以調用另一個對象的方法了),看一個例子就全明白了。
  假設已經有一個UserService類提供了保存User對象的服務,但是現在想增加對User進行驗證的功能,只對通過驗證的User提供保存服務,在不修改UserService類代碼的前提下就可以通過Introduction來解決。

  首先定義一個Verifier接口,里面定義了進行驗證的方法validate(),如下所示

1 public interface Verifier {
2     public boolean validate(User user);
3 }

  接下來給出該接口的一個實現類BasicVerifier,如下所示

1 public class BasicVerifier implements Verifier {
2     @Override
3     public boolean validate(User user) {
4         if(user.getUsername().equals("jack") && user.getPassword().equals("1234")) {
5             return true;
6         }
7         return false;
8     }
9 }

  如何才能為UserService類增加驗證User的功能呢,如下所示定義Aspect:

1 @Aspect
2 @Component
3 public class MyAspect {
4     @DeclareParents(value="com.tsinghuait.services.UserService", 
5             defaultImpl=com.tsinghuait.aop.BasicVerifier.class)
6     public Verifier verifer;
7 }

  接下來就可以將UserService對象轉型為Verifier對象並對用戶進行驗證了,如下所示:

 1 class Test {
 2 
 3     public static void main(String[] args) {
 4         User user1 = new User();
 5         user1.setUsername("abc");
 6         user1.setPassword("def");
 7         
 8         ApplicationContext factory = new ClassPathXmlApplicationContext("config.xml");
 9         Service s = (Service) factory.getBean("service");
10         Verifier v = (Verifier) s;
11         if(v.validate(user1) {
12             System.out.println("驗證成功");
13             s.serve(user1);
14         }
15         
16     }
17 }

  這樣,上面代碼中的user1是不會被服務的,當然是因為沒有通過驗證啦!
  這樣一說,是不是大概明白什么是Introduction了呢,其實@DeclareParents用起來也很簡單吧!


免責聲明!

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



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