• 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

  • 相关阅读:
    Hive是什么
    Hive导入数据的四种方法
    grafana安装
    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
    linux下mysql安装报错及修改密码登录等等
    chown -R 用户名:组名 ./ 及 chown用法介绍
    Hadoop提交作业流程
    Java中常见的几种异常
    mysql索引需要了解的几个注意
    js数组依据下标删除元素
  • 原文地址:https://www.cnblogs.com/jsStudyjj/p/4932248.html
Copyright © 2020-2023  润新知