關於@Autowired 注釋為何不需要get Set


這個我一直讓我想不通,后面iteye上看到了一篇文章才煥然大悟...

在此把文章引用到我blog里面,如下:

 

這段時間用了一下spring 2.5的@Autowired注釋來做依賴注入,感覺真的不錯,省掉了get、set的方法,整個類也看起來更加舒服了。 
在這期間對於@Autowired注釋訪問private的變量一直感到很好奇,查了一下相關資料,寫了一個小例子。不過沒看過@Autowired的源碼,不確定是不是這樣做的,應該差不多吧。 
代碼如下: 

1.聲明了一個注釋 

Java代碼    收藏代碼
  1. @Retention(RetentionPolicy.RUNTIME)  
  2. public @interface TestAnno {  
  3.       
  4. }  



2.聲明了一個含有private變量a的類 

Java代碼    收藏代碼
  1. public class TestAnnotation {  
  2.     @TestAnno  
  3.     private String a;  
  4.   
  5.     public String getA() {  
  6.         return a;  
  7.     }  
  8.   
  9.     public void setA(String a) {  
  10.         this.a = a;  
  11.     }  
  12.   
  13. }  



3.通過反射為a賦值 

Java代碼    收藏代碼
  1. public class MainTest {  
  2.     public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {  
  3.         TestAnnotation ta=new TestAnnotation();  
  4.         Field[] fs=TestAnnotation.class.getDeclaredFields();  
  5.         for(int i=0;i<fs.length;i++){  
  6.             if(fs[i].isAnnotationPresent(TestAnno.class)){  
  7.                 fs[i].setAccessible(true);  
  8.                 fs[i].set(ta, "你好");  
  9.             }  
  10.         }  
  11.         System.out.println(ta.getA());  
  12.     }  
  13. }  


關鍵是fs[i].setAccessible(true);這個方法,如果不設置這個方法則會拋出java.lang.IllegalAccessException的異常。網上也有人說setAccessible有安全性限制不要隨便亂用。不過至少可以做到

 

refer from :http://www.iteye.com/topic/223891


免責聲明!

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



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