zoukankan      html  css  js  c++  java
  • Spring使用标签注解来简化xml书写

    一、步骤

    1. 在配置文件中,引入context命名空间
    <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">

      2.在配置文件中加入context:annotation-config标签

      <context:annotation-config/> 

      这个配置隐式注册了多个对注释进行解析处理的处理器 

      AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor

      PersistenceAnnotationBeanPostProcessorRequiredAnnotationBeanPostProcessor

      注: @Resource注解在spring安装目录的libj2eecommon-annotations.jar

    二、注解详解

    2.1 @Autowired

    这两个注解的区别是:@Autowired 默认按类型装配,@Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。 

     

    @Autowired注解是按类型装配依赖对象,默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required属性为false

     

    2.2  @Qualifier

    如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。如下:

     

    2.3 @Resource 

    1、 @Resource注解和@Autowired一样,也可以标注在字段或属性的setter方法上.

    2、 @Resource注解默认按名称装配。

          名称可以通过@Resourcename属性指定,如果没有指定name属性,

    • 当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象
    • 当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找依赖对象。 
    • 注意:如果没有指定name属性,并且按照默认的名称找不到依赖对象时, @Resource注解会回退到按类型装配。但一旦指定了name属性,就只能按名称装配了。

    2.4 @PostConstruct

      指定Bean的初始化方法

    2.5 @PreDestroy  

      指定Bean的销毁方法

    三、扫描

    使用XMLbean定义来配置组件在一个稍大的项目中,通常会有上百个组件,如果这些组件采用xmlbean定义来配置,显然会增加配置文件的体积,查找及维护起来也不太方便。spring2.5为我们引入了组件自动扫描机制,它可以在类路径底下寻找标注了@Component@Service@Controller@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件是一样的。要使用自动扫描机制,我们需要打开以下配置信息:

    1、引入context命名空间  需要在xml配置文件中配置以下信息:

    <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:component-scan base-package="cn.itcast"/>
    </beans>

    2、在配置文件中添加context:component-scan标签 

     <context:component-scan base-package="cn.*"/>

           其中base-package为需要扫描的包(含子包)

    :

    1、在使用组件扫描元素时,AutowiredAnnotationBeanPostProcessor CommonAnnotationBeanPostProcessor会隐式地被包括进来。 也就是说,连个组件都会被自动检测织入 - 所有这一切都不需要在XML中提供任何bean配置元数据。 

    2、功能介绍

    @Service用于标注业务层组件、

    @Controller用于标注控制层组件(如struts中的action)、

    @Repository用于标注数据访问组件,即DAO组件。

    @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。 

     四、例子

    1.例子来源 

    http://blog.csdn.net/pk490525/article/details/8096326

    spring零配置(Annotation)学习笔记   

    2.本地例子: 

    AnnotationTest

    本地有细小的改变

    project用到的jar包:

    先上bean-config.xml:

    [html] view plaincopy
    
        <?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-3.0.xsd  
                http://www.springframework.org/schema/context  
                http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
                 
            <context:annotation-config/>    
            <!-- action暂未用注解 -->    
            <bean id="myAction" class="com.demo.annotation.action.MyAction" scope="prototype" />  
              
            <!-- 注解测试   -->  
            <context:component-scan base-package="com.demo.annotation" />  
              
              
        </beans> 

    service 接口:

        /** 
         *  
         * Annotation 
         * 
         */  
          
        public interface TestService {  
            /** 
             * 注解测试 
             * @return 
             */  
            public String getTestAnnotation();  
        }  

    service实现类:

        import org.springframework.stereotype.Service;  
          
        import com.demo.annotation.dao.TestDao;  
        import org.springframework.beans.factory.annotation.Autowired;  
        import org.springframework.beans.factory.annotation.Qualifier;  
          
          
          
        /** 
         *  
         * 注解测试 
         * 
         */  
          
        @Service("testService")  
        public class TestServiceImp implements TestService {  
            /** 
             * 自动装配 
             */  
            @Autowired  
            @Qualifier("testDao")  
            //@Resource(name="testDao"), 等价于<property ………… ref="testDao" />   
            private TestDao testDao;  
          
            public TestDao getTestDao() {  
                return testDao;  
            }  
          
            public void setTestDao(TestDao testDao) {  
                this.testDao = testDao;  
            }  
          
          
            @Override  
            public String getTestAnnotation() {  
                // TODO Auto-generated method stub  
                return testDao.getTestDaoAnnotation();  
            }  
          
        }  

    dao接口:

        /** 
         * 测试注解 
         * 
         */  
        public interface TestDao {  
            /** 
             * 得到dao层注解 
             * @return 
             */  
            public String getTestDaoAnnotation();  
        }  

    dao层实现类:

     @Repository("testDao")  
    public class TestDaoImpl implements TestDao {  
      
        @Override  
        public String getTestDaoAnnotation() {  
            // TODO Auto-generated method stub  
            return "This is testDao Annotation...";  
        }  
      
    }  

    Action类:

        import javax.annotation.Resource;  
          
        import com.demo.annotation.service.TestService;  
          
        public class MyAction{  
            @Resource(name="testService")  
            private TestService testService;  
            public String testAnnotation(){  
                if(null == testService){  
                    System.out.println("Service is null!!");  
                }  
                String result = testService.getTestAnnotation();  
                System.out.println(result);  
                return "success";  
            }  
              
            public TestService getTestService() {  
                return testService;  
            }  
          
            public void setTestService(TestService testService) {  
                this.testService = testService;  
            }  
              
        }  

    测试类:

     import org.springframework.context.ApplicationContext;  
    import org.springframework.context.support.ClassPathXmlApplicationContext;  
      
    import com.demo.annotation.action.MyAction;  
      
    public class TestAnnotation {  
        public static void main(String[] args) {  
            ApplicationContext context = new ClassPathXmlApplicationContext("bean-config.xml");  
            MyAction action = (MyAction)context.getBean("myAction");  
            action.testAnnotation();  
              
        }  
    }

     五、注解的原理:

    1.自Java5.0版本引入注解之后,它就成为了Java平台中非常重要的一部分。开发过程中,我们也时常在应用代码中会看到诸如@Override,@Deprecated这样的注解。

      用一个词就可以描述注解,那就是元数据,即一种描述数据的数据。所以,可以说注解就是源代码的元数据。使用Annotation之前(甚至在使用之后),XML被广泛的应用于描述元数据。不知何时开始一些应用开发人员和架构师发现XML的维护越来越糟糕了。他们希望使用一些和代码紧耦合的东西,而不是像XML那样和代码是松耦合的(在某些情况下甚至是完全分离的)代码描述。  

      另一个很重要的因素是Annotation定义了一种标准的描述元数据的方式。在这之前,开发人员通常使用他们自己的方式定义元数据。例如,使用标记interfaces,注释,transient关键字等等。每个程序员按照自己的方式定义元数据,而不像Annotation这种标准的方式。

      目前,许多框架将XML和Annotation两种方式结合使用,平衡两者之间的利弊。

    2.自定义一个简单的注解:

    ①类注解:

    package com.kun.annotation;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target(ElementType.TYPE)  //作用范围是类
    @Retention(RetentionPolicy.RUNTIME)  //运行时生效
    public @interface ClassInfo {
        String name() default "";
    }

    ②方法注解:

    package com.kun.annotation;
    
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target(ElementType.METHOD)    //作用范围是方法
    @Retention(RetentionPolicy.RUNTIME)
    public @interface MethodInfo {
        String name() default "";
    }

    ③注解解析:

    package com.kun.annotation;
    
    import java.lang.annotation.Target;
    import java.lang.reflect.Method;
    
    import org.junit.Test;
    
    
    public class AnnotationParse {
        public static void parse(){
            Class class1 = Annotation_kun.class;
            //该类上面是否存在ClassInfo注解
            if(class1.isAnnotationPresent(ClassInfo.class)){
                //获取类上面的ClassInfo注解
                ClassInfo classInfo = (ClassInfo)class1.getAnnotation(ClassInfo.class);
                System.out.println(classInfo.name());
            }
            
            Method[] methods = class1.getMethods();
            for (Method method : methods) {
                //判断该方法上面是否存在MethodInfo注解
                if(method.isAnnotationPresent(MethodInfo.class)){
                    //获取到方法上面的注解
                    MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);
                    System.out.println(methodInfo.name());
                }
            }
        }
        
        @Test
        public void test(){
            AnnotationParse.parse();
        }
    }

    ④应用:

    package com.kun.annotation;
    
    @ClassInfo(name="类注解生效")
    public class Annotation_kun {
        @MethodInfo(name="方法注解生效")
        public void java(){
            
        }
    }
  • 相关阅读:
    安全性
    黄保翕的书总结
    Week14(12月11日):路由
    Week14(12月9日)
    Week13(12月5日):不怕错误,慢慢来 :)
    必会技能
    eclipse建maven pom报错
    查看Linux连接数
    查mysql字段中的数字记录
    清理c盘检查
  • 原文地址:https://www.cnblogs.com/liuyk-code/p/6728923.html
Copyright © 2011-2022 走看看