一、步骤

  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/>

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

  AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,

  PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor

 注: @Resource注解在spring安装目录的lib\j2ee\common-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注解默认按名称装配。

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

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

2.4 @PostConstruct

  指定Bean的初始化方法

2.5 @PreDestroy

  指定Bean的销毁方法

三、扫描

使用XML的bean定义来配置组件在一个稍大的项目中,通常会有上百个组件,如果这些组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找及维护起来也不太方便。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(){ }
}

Spring使用标签注解来简化xml书写的更多相关文章

  1. (D)spring boot使用注解类代替xml配置实例化bean

    bean经常需要被实例化,最常见的就是new一个呗,Bean bean = new Bean(),方便好用还快捷. 然而在我们刚开始学习写i项目的时候却发现,new不好用哦,并且也不报错,根本不知道怎 ...

  2. spring 注入使用注解(不用xml)

    (一):导入spring4的jar包 (二):在xml中配置扫描的包 <context:component-scan base-package="entity">< ...

  3. Spring 3.0 注解

    原文 :http://www.blogjava.net/ashutc/archive/2011/04/14/348270.html 另两 参考博客 : http://kingtai168.iteye. ...

  4. Spring 自定义标签配置

    前景:经常使用一些依赖于Spring的组件时,发现可以通过自定义配置Spring的标签来实现插件的注入,例如数据库源的配置,Mybatis的配置等.那么这些Spring标签是如何自定义配置的?学习Sp ...

  5. 使用Spring注解来简化ssh框架的代码编写

     目的:主要是通过使用Spring注解的方式来简化ssh框架的代码编写. 首先:我们浏览一下原始的applicationContext.xml文件中的部分配置. <bean id="m ...

  6. Spring+MyBatis纯注解零XML整合(4)

    不得不说,利用XML作为配置文件是一个非常好的想法,它可以轻松地实现配置集中化,而且修改之后无需再次编译.然而,由于大多数情况下开发者基本都会拿到程序的源码,加之对于各种XML配置文件一般情况下也只有 ...

  7. Unit03: Spring Web MVC简介 、 基于XML配置的MVC应用 、 基于注解配置的MVC应用

    Unit03: Spring Web MVC简介 . 基于XML配置的MVC应用 . 基于注解配置的MVC应用 springmvc (1)springmvc是什么? 是一个mvc框架,用来简化基于mv ...

  8. spring mvc常用注解标签

    @Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model , ...

  9. spring : springmvc常用注解标签详解(转)

    新的项目,新的学习,好久没用这些注解了,同时在学习使用shiro ,lucene 等等.在网上找了些博文,感谢作者的总结和分享. 欢迎交流,言归正传: 1.@Controller 在SpringMVC ...

随机推荐

  1. win+D可以最小化所有窗口,显示桌面 win+E可以快速打开我的电脑 这两个对我来说非常常用,要用熟练,节约时间

    win+D可以最小化所有窗口,显示桌面   win+E可以快速打开我的电脑

  2. Ubuntu源更新

    Ubuntu12.04的源在 /etc/apt/sources.list  中, 进入 /etc/apt/ 先进行备份 然后用根用户权限打开sources.list. sudo gedit /etc/ ...

  3. 你不知道的sticky

    position:sticky,Chrome新版本已经做了支持.sticky的中文翻译是“粘性的”,position:sticky表现也符合这个粘性的表现.基本上,可以看出是position:rela ...

  4. Android平台下渗透测试工具大集合

    Android平台下渗透测试工具大集合 分享一个google的项目,各种Android下的渗透测试工具. Ad Network Detector (1.2): http://market.androi ...

  5. 随想录(skyeye中的soc仿真)

    [ 声明:版权所有,欢迎转载,请勿用于商业用途. 联系信箱:feixiaoxing @163.com] 想学好soc,再怎么看芯片手册和linux kernel都不为过.但是要学习好kernel,那再 ...

  6. Ubuntu安装最新版的nodejs

    安装玩Ubuntu的虚拟机之后安装nodejs发现npm的版本才3.5.2,这都多老了?于是Google了一下,发现是由于Ubuntu官方维护的包源太老了,想要安装nodejs的最新版,两种方法,一种 ...

  7. OpenCV-Python cv2.imdecode()和cv2.imencode() 图片解码和编码

    cv2.imdecode()函数从指定的内存缓存中读取数据,并把数据转换(解码)成图像格式;主要用于从网络传输数据中恢复出图像. cv2.imencode()函数是将图片格式转换(编码)成流数据,赋值 ...

  8. SHELL 脚本----常用的命令

    一个很不错的bash脚本编写教程,至少没接触过BASH的也能看懂   建立一个脚本 Linux中有好多中不同的shell,但是通常我们使用bash (bourne again shell) 进行she ...

  9. zend studio 提升开发效率的快捷键及可视化订制相关设置

    Zend studio快捷键使用 F3 快速跳转到当前所指的函数,常量,方法,类的定义处,相当常用.当然还可以用Ctrl+鼠标左键 shift+end 此行第一个到最后一个 shift+home 此行 ...

  10. 神奇的TextField(1)

    先看一大段测试代码,每个小方法的注释行是输出结果. private var text_content:TextField; private function textFieldDemo():void{ ...