本文主要分为三部分:

一、 注解的基本概念和原理及其简单实用

二、 Spring中如何使用注解

三、 编码剖析spring@Resource的实现原理

一、注解的基本概念和原理及其简单实用

注解(Annotation)提供了一种安全的类似注释的机制,为我们在代码中添加信息提供了一种形式化得方法,使我们可以在稍后某个时刻方便的使用这些数据(通过解析注解来使用这些数据),用来将任何的信息或者元数据与程序元素(类、方法、成员变量等)进行关联。其实就是更加直观更加明了的说明,这些说明信息与程序业务逻辑没有关系,并且是供指定的工具或框架使用的。Annotation像一种修饰符一样,应用于包、类型、构造方法、方法、成员变量、参数及本地变量的申明语句中。

Annotation其实是一种接口。通过java的反射机制相关的API来访问Annotation信息。相关类(框架或工具中的类)根据这些信息来决定如何使用该程序元素或改变它们的行为。Java语言解释器在工作时会忽略这些Annotation,因此在JVM中这些Annotation是“不起作用”的,只能通过配套的工具才能对这些Annotation类型的信息进行访问和处理。

Annotation和interface的异同:

1、 annotition的类型使用关键字@interface而不是interface。它继承了java.lang.annotition.Annotition接口,并非申明了一个interface。

2、 Annotation类型、方法定义是独特的、受限制的。Annotation类型的方法必须申明为无参数、无异常抛出的。这些方法定义了Annotation的成员:方法名称为了成员名,而方法返回值称为了成员的类型。而方法返回值必须为primitive类型、Class类型、枚举类型、Annotation类型或者由前面类型之一作为元素的一位数组。方法的后面可以使用default和一个默认数值来申明成员的默认值,null不能作为成员的默认值,这与我们在非Annotation类型中定义方法有很大不同。Annotation类型和他的方法不能使用Annotation类型的参数,成员不能是generic。只有返回值类型是Class的方法可以在Annotation类型中使用generic,因为此方法能够用类转换将各种类型转换为Class。

3、 Annotation类型又与接口有着近似之处。它们可以定义常量、静态成员类型(比如枚举类型定义)。Annotation类型也可以如接口一般被实现或者继承。

* 元注解@Target,@Retention,@Documented,@Inherited 

* @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括: 
* ElemenetType.CONSTRUCTOR 构造器声明 
* ElemenetType.FIELD 域声明(包括 enum 实例) 
* ElemenetType.LOCAL_VARIABLE 局部变量声明 
* ElemenetType.METHOD 方法声明 
* ElemenetType.PACKAGE 包声明 
* ElemenetType.PARAMETER 参数声明 
* ElemenetType.TYPE 类,接口(包括注解类型)或enum声明 

* @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括: 
* RetentionPolicy.SOURCE 注解将被编译器丢弃 
* RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 
* RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。 

* @Documented 将此注解包含在 javadoc 中 

* @Inherited 允许子类继承父类中的注解

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

----------------------------------------Demo----------------------------------------------------

package com.wxy.annotation;
 
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType; 
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**   
*  定义注解Test
*  注解中含有两个元素 id 和 description
*  description元素有默认值"no description"  
*   @create-time     2011-8-12   下午02:22:28   
*   @revision          $Id
*/
 
//该注解用于方法声明
@Target(ElementType.METHOD)
//VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息
@Retention(RetentionPolicy.RUNTIME)
//将此注解包含在javadoc中
@Documented
//允许子类继承父类中的注解
@Inherited

public @interface Test { 
    public int id();
    public String description() default "no description";
}
package com.wxy.annotation;
import java.lang.reflect.Method;
/**
*   使用注解和解析注解
*  
*   @creator            xiaoyu.wang   
*   @create-time     2011-8-12   下午03:49:17   
*   @revision          $Id
*/
public class Test_1{
    /**
     * 被注释的三个方法
     */
    @Test(id = 1, description = "hello method1")
    public void method1() {
    }

    @Test(id = 2)
    public void method2() {
    }

    @Test(id = 3, description = "last method3")

    /**
     * 解析注释,将Test_1类所有被注解方法的信息打印出来
     * @param args
     */
    public static void main(String[] args) {
        Method[] methods = Test_1.class.getDeclaredMethods();
        for (Method method : methods) {
            //判断方法中是否有指定注解类型的注解
            boolean hasAnnotation = method.isAnnotationPresent(Test.class);
            if (hasAnnotation) {
                //根据注解类型返回方法的指定类型注解
                Test annotation = method.getAnnotation(Test.class);
                System.out.println("Test(method=" + method.getName() + ",id=" + annotation.id()
                                   + ",description=" + annotation.description() + ")");
            }
        }
    }
}

Spring @Resource注解实现原理编码分析

二、spring中注解@Resource的使用

1、修改bean.xml,引入命名空间(保证项目能引用到common-annotations.jar)

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns=http://www.springframework.org/schema/beans
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context=http://www.springframework.org/schema/context
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    <context:annotation-config />
         <bean id="peopleDao" class="com.wxy.dao.impl.PeopleDaoBean"></bean>
         <bean id="peopleService" class="com.wxy.service.impl.PeopleServiceBean"       
         </bean>
</beans> 

2、在PeopleServiceBean中使用@Resource注解

public class PeopleServiceBean implements PeopleService {
    @Resource
    private PeopleDao peopleDao;
    private String    name = "wxy";
    private Integer   id   = 1;
}

3、 测试:

   public class Test {
    public static void main(String[] args) {
        //IOC容器实例化
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        PeopleService peopleService = (PeopleService) ac.getBean("peopleService");
        peopleService.save();
    }
}

4、 结果:

 --> the method is called save()! name=wxy,id=1
this is the method PeopleDaoBean.add()!

也可以在setter方法上使用@Resource:

public class PeopleServiceBean implements PeopleService {
    private PeopleDao peopleDao;
    private String    name = "wxy";
    private Integer   id   = 1;

    /** 
     * @return the peopleDao
     */
    public PeopleDao getPeopleDao() {
        return peopleDao;
    }
 
    /**
     * @param peopleDao the peopleDao to set
     */
    @Resource
    public void setPeopleDao(PeopleDao peopleDao) {
        this.peopleDao = peopleDao;
}
    …..
}

结果一样。

三、@Resource注解的实现原理(只用于配置,不用于干活)

1、新建Annotation类型文件

 package com.wxy.annotation;
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.FIELD, ElementType.METHOD })
public @interface WxyResource {
    String name() default "";
}

2、使用自定义的注解@WxyResource

 public class PeopleServiceBean implements PeopleService {
    private PeopleDao peopleDao;
    private String    name = "wxy";
    private Integer   id   = 1;

    /** 
     * @param peopleDao the peopleDao to set
     */
    @WxyResource
    public void setPeopleDao(PeopleDao peopleDao) {
        this.peopleDao = peopleDao;
}
}

3、事实上上一步没有实现,这一步开始实现注入原理,在自定义spring容器中添加注解功能

public class WxyClassPathXMLApplicationContext {
 
    //存放BeanDefinition的列表,在beans.xml中定义的bean可能不止一个
    private final List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
    //将类名作为索引,将创建的Bean对象存入到Map中
    private final Map<String, Object>  sigletons   = new HashMap<String, Object>();
    public WxyClassPathXMLApplicationContext(String fileName) {
        //读取xml配置文件
        this.readXML(fileName);
        //实例化bean
        this.instanceBeans();
        //处理注解方式
        this.annotationInject();
        //注入对象
        this.injectObject();
    }

    /** 
     * 使用注解方式注入对象方法实现
     * @throws IntrospectionException 
     */
    private void annotationInject() {
        //循环所有bean对象
        for (String beanName : sigletons.keySet()) {
            //获取bean对象
            Object bean = sigletons.get(beanName);
            //如果bean不为空,取得bean的属性
            if (bean != null) {
                try {
                    //按属性注入
                    PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass())
                        .getPropertyDescriptors();
                    for (PropertyDescriptor properdesc : ps) {
                        //获取属性的setter方法
                        Method setter = properdesc.getWriteMethod();
                        //判断注解是否存在
                        if (setter != null && setter.isAnnotationPresent(WxyResource.class)) {
                            //取得注解
                            WxyResource resource = setter.getAnnotation(WxyResource.class);
                            Object value = null;
                            //如果按名字找到
                            if (resource.name() != null && !"".equals(resource.name())) {
                                //取得容器中的bean对象
                                value = sigletons.get(resource.name());
 
                            } else {//没有按名字找到,按类型寻找
                                //取得容器中的bean对象
                                value = sigletons.get(resource.name());
                                if (value == null) {
                                    for (String key : sigletons.keySet()) {
                                        if (properdesc.getPropertyType().isAssignableFrom(
                                            sigletons.get(key).getClass())) {
                                            value = sigletons.get(key);
                                            break;
                                        }
                                    }
                                }
                            }

                            //把引用对象注入到属性
                            setter.setAccessible(true); 
                            setter.invoke(bean, value);
                        }
                    }
                    //按字段注入
                    Field[] fields = bean.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        //如果注解存在
                        if (field.isAnnotationPresent(WxyResource.class)) {
                            //取得注解
                            WxyResource resource = field.getAnnotation(WxyResource.class);
                            Object value = null;
                            //如果按名字找到
                            if (resource.name() != null && !"".equals(resource.name())) {
                                //取得容器中的bean对象
                                value = sigletons.get(resource.name());
                            } else {//没有按名字找到,按类型寻找
                                //取得容器中的bean对象
                                value = sigletons.get(field.getName());
                                if (value == null) {
                                    for (String key : sigletons.keySet()) {
                                        if (field.getType().isAssignableFrom(
                                            sigletons.get(key).getClass())) {
                                            value = sigletons.get(key);
                                            break;
                                        }
                                    }
                                }
                            }

                            //允许访问private 
                            field.setAccessible(true);
                            field.set(bean, value);
                        }
                    }
                } catch (IntrospectionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    /** 
     *为bean对象的属性注入值
     */
private void injectObject() {
….
}
….
}

4、 使用自定义容器测试:

 public class MyTest { 
    /**
     * @param args
     */
    public static void main(String[] args) {
        //MyIOC容器实例化
        WxyClassPathXMLApplicationContext ac = new WxyClassPathXMLApplicationContext("beans.xml");
        PeopleService peopleService = (PeopleService) ac.getBean("peopleService");
        peopleService.save();
    }
}

6、 测试结果:

--> the method is called save()! name=wxy,id=1
this is the method PeopleDaoBean.add()!

注解本身不做任何事情,只是像xml文件一样起到配置作用。注解代表的是某种业务意义,注解背后处理器的工作原理如上源码实现:首先解析所有属性,判断属性上是否存在指定注解,如果存在则根据搜索规则取得bean,然后利用反射原理注入。如果标注在字段上面,也可以通过字段的反射技术取得注解,根据搜索规则取得bean,然后利用反射技术注入。

Spring注解原理的详细剖析与实现的更多相关文章

  1. [转]Spring注解原理的详细剖析与实现

    原文地址:http://freewxy.iteye.com/blog/1149128/ 本文主要分为三部分: 一.注解的基本概念和原理及其简单实用 二.Spring中如何使用注解 三.编码剖析spri ...

  2. Spring 注解原理(三)@Qualifier @Value

    Spring 注解原理(三)@Qualifier @Value Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) 一.Aut ...

  3. Spring 注解原理(一)组件注册

    Spring 注解原理(一)组件注册 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) 当我们需要使用 Spring 提供的 ...

  4. Spring注解原理

    一.注解的基本概念和原理及其简单实用 注解(Annotation)提供了一种安全的类似注释的机制,为我们在代码中添加信息提供了一种形式化得方法,使我们可以在稍后某个时刻方便的使用这些数据(通过解析注解 ...

  5. Spring注解之@Component详细解析

    @controller 控制器(注入服务) 2.@service 服务(注入dao) 3.@repository dao(实现dao访问) 4.@component (把普通pojo实例化到sprin ...

  6. Spring 中常用注解原理剖析

    前言 Spring 框架核心组件之一是 IOC,IOC 则管理 Bean 的创建和 Bean 之间的依赖注入,对于 Bean 的创建可以通过在 XML 里面使用 <bean/> 标签来配置 ...

  7. 【spring 注解驱动开发】Spring AOP原理

    尚学堂spring 注解驱动开发学习笔记之 - AOP原理 AOP原理: 1.AOP原理-AOP功能实现 2.AOP原理-@EnableAspectJAutoProxy 3.AOP原理-Annotat ...

  8. 浅尝Spring注解开发_AOP原理及完整过程分析(源码)

    浅尝Spring注解开发_AOP原理及完整过程分析(源码) 浅尝Spring注解开发,基于Spring 4.3.12 分析AOP执行过程及源码,包含AOP注解使用.AOP原理.分析Annotation ...

  9. 【Spring注解驱动开发】自定义组件如何注入Spring底层的组件?看了这篇我才真正理解了原理!!

    写在前面 最近,很多小伙伴出去面试都被问到了Spring问题,关于Spring,细节点很多,面试官也非常喜欢问一些很细节的技术点.所以,在 Spring 专题中,我们尽量把Spring的每个技术细节说 ...

随机推荐

  1. bzoj 4921: [Lydsy六月月赛]互质序列

    4921: [Lydsy六月月赛]互质序列 Time Limit: 1 Sec  Memory Limit: 256 MBSubmit: 188  Solved: 110[Submit][Status ...

  2. 公共返回JSON信息的方法

    java代码: public void returnMessage(HttpServletResponse response, Object str){ PrintWriter write = nul ...

  3. 邁向IT專家成功之路的三十則鐵律 鐵律十八:IT人求職之道-文化

    IT人所從事的工作是一個求新求變速度最快的行業,因此您所待的企業IT部門或資訊公司,其組織文化將關係到您在這間公司服務期間,是否能夠快速成長的決定因素.遇到不良的組織文化建議您三個就可以走人了,千萬別 ...

  4. [反汇编练习] 160个CrackMe之035

    [反汇编练习] 160个CrackMe之035. 本系列文章的目的是从一个没有任何经验的新手的角度(其实就是我自己),一步步尝试将160个CrackMe全部破解,如果可以,通过任何方式写出一个类似于注 ...

  5. K-L变换和 主成分分析PCA

    一.K-L变换 说PCA的话,必须先介绍一下K-L变换了. K-L变换是Karhunen-Loeve变换的简称,是一种特殊的正交变换.它是建立在统计特性基础上的一种变换,有的文献也称其为霍特林(Hot ...

  6. python(8)- python基础数据类型

    数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视 频.网页等各种各样的数据,不同的数据,需要 ...

  7. JavaScript 工厂模式和订阅模式

    设计模式的好处: 代码规范 // 例如表单验证,两个 input ,一个用户名,一个密码 // 通常做法是 function checkUser(){ //..... } function check ...

  8. 系统安全-PAM

    Pluggable Authentication Modules(可插入验证模块,简称PAM) Linux-PAM(Pluggable Authentication Modules for Linux ...

  9. smartUpload注意过程

    操作的过程中一定要注意的几个方面:       1.将smartUpload.jar拷贝到tomcat/lib以及项目的lib下面,最好是只多不少!       2.因为上传的文件一般都很大,所以应该 ...

  10. session自己定义存储,怎样更好地进行session共享;读tomcat7源代码,org.apache.catalina.session.FileStore可知

    session自己定义存储.怎样更好地进行session共享: 读tomcat源代码,org.apache.catalina.session.FileStore可知 一.详见: 方法1 public ...