spring @Autowired注入的原理

只知道如何用Autowired注解,知道可以替代set,get方法,很方便,却一直不知道,为什么可以代替

今天探索一下原因,所谓知其然还要知其所以然,才能理解的更好,记忆的更牢,才能转化为自己的知识。

 

这都是利用了java的注解原理:

如下:

1.先定义一个注解

1 /** 
2  * @author jing.ming
3  * @version 创建时间:2015年11月3日 上午9:35:03 
4  * 声明一个注解
5  */
6 @Retention(RetentionPolicy.RUNTIME)
7 public @interface TestAnno {
8 
9 }

2.定义一个类

 1 /** 
 2  * @author jing.ming
 3  * @version 创建时间:2015年11月3日 上午9:37:34 
 4  * 程序的简单说明 
 5  */
 6 public class TestAnnotation {
 7 
 8     @TestAnno
 9     private String a ;
10     
11     public String getA(){
12         return a ;
13     }
14     public void setA(String a){
15         this.a = a ;
16     }
17 }

3.通过反射为上面的类赋值

 1 /** 
 2  * @author jing.ming
 3  * @version 创建时间:2015年11月3日 上午9:39:47 
 4  * 通过反射为a赋值
 5  */
 6 public class MainReflectTest {
 7 
 8     public static void main(String[] args) {
 9         TestAnnotation ta = new TestAnnotation() ;
10         Field[] fs = TestAnnotation.class.getDeclaredFields();
11         for(int i=0;i<fs.length;i++){
12             if(fs[i].isAnnotationPresent(TestAnno.class)){
13                 fs[i].setAccessible(true);
14                 try {
15                     fs[i].set(ta, "Hello World");
16                 } catch (IllegalArgumentException e) {
17                     e.printStackTrace();
18                 } catch (IllegalAccessException e) {
19                     e.printStackTrace();
20                 }
21             }
22         }
23  
24         System.out.println(ta.getA());
25     }
26 
27 }

关键是fs[i].setAccessible(true);这个方法,如果不设置这个方法则会抛出java.lang.IllegalAccessException的异常。网上也有人说setAccessible有安全性限制不要随便乱用。不过至少可以做到.

这里有一个详细的讲解:

http://swiftlet.net/archives/734

posted on 2015-11-03 09:55  明静  阅读(5193)  评论(0编辑  收藏  举报

导航