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

來源:互聯網
上載者:User

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

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

 

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

1.聲明了一個注釋  @Retention(RetentionPolicy.RUNTIME)   public @interface TestAnno {          }  



2.聲明了一個含有private變數a的類  public class TestAnnotation {       @TestAnno       private String a;          public String getA() {           return a;       }          public void setA(String a) {           this.a = a;       }      }  



3.通過反射為a賦值  public class MainTest {       public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {           TestAnnotation ta=new TestAnnotation();           Field[] fs=TestAnnotation.class.getDeclaredFields();           for(int i=0;i<fs.length;i++){               if(fs[i].isAnnotationPresent(TestAnno.class)){                   fs[i].setAccessible(true);                   fs[i].set(ta, "你好");               }           }           System.out.println(ta.getA());       }   }  


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.