2016-04-29 79 views
1

問:春天在非託管的彈簧組件,如域對象運行點切的表達?從我的實驗看來,它沒有,那麼在常規對象上運行切入點表達式的最佳方式是什麼?域AspectJ切入點表達式對象不受Spring管理

我創建自定義註解的名稱@Encrypt,這樣,當它是在一個域對象使用上的場的頂部,該字段被髮送到web服務,並且自動加密。

我第一次開始使用方法級別的註釋,發現切入點表達不上不是由Spring管理對象的工作,它必須是一個Spring bean。

1. Spring指標:檢查自定義註釋@Encrypt並打印出來。

@Aspect 
public class EncryptAspect { 

    @Around("@annotation(encrypt)") 
    public Object logAction(ProceedingJoinPoint pjp, Encrypt encrypt) 
      throws Throwable { 

     System.out.println("Only encrypt annotation is running!"); 
     return pjp.proceed(); 
    } 
} 

2.定製譯註:使用

@Documented 
@Target(ElementType.METHOD) 
@Retention(RetentionPolicy.RUNTIME) 

public @interface Encrypt 
{ 
    // Handled by EncryptFieldAspect 
} 

3. Domain對象註釋

public interface CustomerBo { 
    void addCustomerAround(String name); 
} 

public class CustomerBoImpl implements CustomerBo {  
    @Encrypt 
    public void addCustomerAround(String name){ 
     System.out.println("addCustomerAround() is running, args : " + name); 
    } 
} 

4.調用

 ApplicationContext appContext = new ClassPathXmlApplicationContext("http-outbound-config.xml"); 
//  CustomerBoImpl customer = new CustomerBoImpl(); --> Aspect is not fired if object is created like this. 
     CustomerBo customer = (CustomerBo) appContext.getBean("customerBo"); // Aspect Works 
     customer.addCustomerAround("test"); 
+0

這似乎是一個XY問題(請參閱:http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。你能解釋一下,你想要什麼時候運行加密?換句話說,你正試圖解決的問題。 – Apokralipsa

+0

@Apokralipsa我更新了我的問題,希望這個清楚。 –

回答

2

第一個問題(「春天在非託管的彈簧組件,如域對象運行點切表情?」)的答案是否定的。 Spring reference manual has a chapter that exactly explains how Spring AOP works and why it won't work in that case

我看到的選項(在如何我最有可能的做法這個問題的順序):

  1. 滴速方面和封裝這種不變的服務或工廠,創建CustomerBo的。如果CustomerBoImpl是不可變的,那麼最好是這樣,這樣你就不必擔心它會被解密並且處於不正確的狀態。
  2. 如果您使用的是Java持久性API(JPA)堅持你的域對象,如果它是確定的加密保存在數據庫中之前,你就跑,你可能需要使用listeners(注:該鏈接指向把Hibernate的文檔,這是JPA的實現)
  3. 核選項之一 - 實際上切換到使用AspectJ,可以引入諮詢,構造函數,字段值的更改等
+0

謝謝,我選擇了AspectJ。你也可以嘗試回答這個問題,我對aspectJ .. http://stackoverflow.com/questions/36974974/converting-code-based-style-to-annotation-based-style-aop-using-spring-or-方面 –