Spring使用标签注解来简化xml书写
一、步骤
- 在配置文件中,引入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书写的更多相关文章
- (D)spring boot使用注解类代替xml配置实例化bean
bean经常需要被实例化,最常见的就是new一个呗,Bean bean = new Bean(),方便好用还快捷. 然而在我们刚开始学习写i项目的时候却发现,new不好用哦,并且也不报错,根本不知道怎 ...
- spring 注入使用注解(不用xml)
(一):导入spring4的jar包 (二):在xml中配置扫描的包 <context:component-scan base-package="entity">< ...
- Spring 3.0 注解
原文 :http://www.blogjava.net/ashutc/archive/2011/04/14/348270.html 另两 参考博客 : http://kingtai168.iteye. ...
- Spring 自定义标签配置
前景:经常使用一些依赖于Spring的组件时,发现可以通过自定义配置Spring的标签来实现插件的注入,例如数据库源的配置,Mybatis的配置等.那么这些Spring标签是如何自定义配置的?学习Sp ...
- 使用Spring注解来简化ssh框架的代码编写
目的:主要是通过使用Spring注解的方式来简化ssh框架的代码编写. 首先:我们浏览一下原始的applicationContext.xml文件中的部分配置. <bean id="m ...
- Spring+MyBatis纯注解零XML整合(4)
不得不说,利用XML作为配置文件是一个非常好的想法,它可以轻松地实现配置集中化,而且修改之后无需再次编译.然而,由于大多数情况下开发者基本都会拿到程序的源码,加之对于各种XML配置文件一般情况下也只有 ...
- Unit03: Spring Web MVC简介 、 基于XML配置的MVC应用 、 基于注解配置的MVC应用
Unit03: Spring Web MVC简介 . 基于XML配置的MVC应用 . 基于注解配置的MVC应用 springmvc (1)springmvc是什么? 是一个mvc框架,用来简化基于mv ...
- spring mvc常用注解标签
@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model , ...
- spring : springmvc常用注解标签详解(转)
新的项目,新的学习,好久没用这些注解了,同时在学习使用shiro ,lucene 等等.在网上找了些博文,感谢作者的总结和分享. 欢迎交流,言归正传: 1.@Controller 在SpringMVC ...
随机推荐
- 【python】numpy pandas 特性(随时更新)
[value map] 用df.replace(dict)可以解决.但是如果dict太大,会非常非常慢. [array相加的维度规律][广播] (2,3) 能和 (3,) 相加,不能和(2,)相加 ( ...
- oracle 存储过程心得2
1.退出存储过程 return if old_save_time = new_save_time then--没有最新数据,退出 insert into hy_data_handle_mark(id, ...
- 如何快速上手.net下单元测试工具NUnit?
NUnit基本使用 准备知识: 读此博文需要了解单元测试基本概念及NUnit的的安装. 传送门:单元测试之道(使用NUnit) 1.常见的错误 当学习一个新东西时,先学习错误,是最快的方式. 1.1 ...
- Android中的service
1.service简介:service可以在和多场合的应用中使用,比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测SD卡上文件的变化,再或者在后台记录你地理信息 ...
- sapconnector.dll download
Sapnoc30Demo_Yan.rar Sap30Server.rar SAPNCO_Sample_Code.zip sapcon3.0_X64.rar DbEntry.Net.4.1.Setup. ...
- JavaScript 与 Java、PHP 的比较
网站开发的实践从设计方面开始,包括客户端编程语言.大体上说,在网页设计中使用了三种语言:HTML,CSS和Java.自从网站发明以来,HTML和CSS已经成为网页设计的基础,但是Java被用于添加网站 ...
- 使用PHP判断是否为微信、支付宝等移动设备访问代码
在开发过程中经常遇到根据不同的设备显示不同的数据或者在页面样式上做不同的布局,另外在做支付接口的时候也可能会判断当前是什么设备访问,例如判断如果是微信内置浏览器访问则只启用微信支付功能,如果是支付宝内 ...
- elasticsearch 动态模板
在elasticsearch中,如果你有一类相似的数据字段,想要统一设置其映射,就可以用到一项功能:动态模板映射(dynamic_templates). 每个模板都有一个名字用于描述这个模板的用途,一 ...
- 脚本工具---自动解析mysql建表语句,生成sqlalchemy表对象声明
常规建表语句: CREATE TABLE `test_table` ( `id` int(11) NOT NULL, `name` char(64) NOT NULL, `password` char ...
- Yii CDbCriteria类中方法
$criteria = new CDbCriteria; //select $criteria->select = '*';//默认* $criteria->select = 'id,na ...