- 浏览: 508692 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (422)
- 重要 (12)
- BUG解决备忘录 (32)
- 环境搭建 (17)
- 开源组件 (4)
- 数据库 (16)
- 设计模式 (4)
- 测试 (3)
- javascript (5)
- Android (14)
- jdk相关 (9)
- struts2 (10)
- freemark (3)
- 自定义扩展及工具类 (5)
- jdk5新特性及java基础 (13)
- ssh及其他框架 (15)
- linux (32)
- tcp-ip http协议 (8)
- 服务器集群与负载均衡 (34)
- 项目管理相关 (11)
- 实用小技术 (10)
- 架构相关 (14)
- firefox组件 (11)
- spider (6)
- 产品设计 (11)
- PHP (1)
- ws (4)
- lucene (10)
- 其他 (2)
- BI (1)
- NoSQL (3)
- gzip (1)
- ext (4)
- db (6)
- socket (1)
- 源码阅读 (2)
- NIO (2)
- 图片处理 (1)
- java 环境 (2)
- 项目管理 (4)
- 从程序员到项目经理(一):没有捷径 (1)
- bug (1)
- JAVA BASE (8)
- 技术原理 (0)
- 新框架新技术 (1)
- 量化与python (1)
- 系统编程 (0)
- C语言 (0)
- 汇编 (0)
- 算法 (0)
最新评论
-
hyspace:
别逗了,最后一个算法根本不是最优的,sort(function ...
数组去重——一道前端校招试题 -
washingtin:
楼主能把策略和路由的类代码贴出来吗
Spring + iBatis 的多库横向切分简易解决思路 -
sdyjmc:
初略看了一下,没有闹明白啊,均衡负载使用Nginx,sessi ...
J2EE集群原理 I -
shandeai520:
谢谢大神!请教大神一个问题:假如我有三台服务器,连接池的上限是 ...
集群和数据库负载均衡的研究 -
hekuilove:
给lz推荐一下apache commonsStringUtil ...
request 获取 ip
1. 使用Spring注解来注入属性
1.1. 使用注解以前我们是怎样注入属性的
类的实现:
- public class UserManagerImpl implements UserManager {
- private UserDao userDao;
- public void setUserDao(UserDao userDao) {
- this .userDao = userDao;
- }
- ...
- }
public class UserManagerImpl implements UserManager { private UserDao userDao; public void setUserDao(UserDao userDao) { this.userDao = userDao; } ... }
配置文件:
- <bean id= "userManagerImpl" class = "com.kedacom.spring.annotation.service.UserManagerImpl" >
- <property name="userDao" ref= "userDao" />
- </bean>
- <bean id="userDao" class = "com.kedacom.spring.annotation.persistence.UserDaoImpl" >
- <property name="sessionFactory" ref= "mySessionFactory" />
- </bean>
<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl"> <property name="userDao" ref="userDao" /> </bean> <bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl"> <property name="sessionFactory" ref="mySessionFactory" /> </bean>
1.2. 引入@Autowired注解(不推荐使用,建议使用@Resource)
类的实现(对成员变量进行标注)
- public class UserManagerImpl implements UserManager {
- @Autowired
- private UserDao userDao;
- ...
- }
public class UserManagerImpl implements UserManager { @Autowired private UserDao userDao; ... }
或者(对方法进行标注)
- public class UserManagerImpl implements UserManager {
- private UserDao userDao;
- @Autowired
- public void setUserDao(UserDao userDao) {
- this .userDao = userDao;
- }
- ...
- }
public class UserManagerImpl implements UserManager { private UserDao userDao; @Autowired public void setUserDao(UserDao userDao) { this.userDao = userDao; } ... }
配置文件
- <bean id= "userManagerImpl" class = "com.kedacom.spring.annotation.service.UserManagerImpl" />
- <bean id="userDao" class = "com.kedacom.spring.annotation.persistence.UserDaoImpl" >
- <property name="sessionFactory" ref= "mySessionFactory" />
- </bean>
<bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl" /> <bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl"> <property name="sessionFactory" ref="mySessionFactory" /> </bean>
@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。以上两种不同实现方式中,@Autowired的标注位置
不同,它们都会在Spring在初始化userManagerImpl这个bean时,自动装配userDao这个属性,区别是:第一种实现
中,Spring会直接将UserDao类型的唯一一个bean赋值给userDao这个成员变量;第二种实现中,Spring会调用
setUserDao方法来将UserDao类型的唯一一个bean装配到userDao这个属性。
1.3. 让@Autowired工作起来
要使@Autowired能够工作,还需要在配置文件中加入以下代码
- <bean class = "org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
1.4. @Qualifier
@Autowired是根据类型进行自动装配的。在上面的例子中,如果当Spring上下文中存在不止一个UserDao类型的bean时,就会
抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出
BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。
1. 可能存在多个UserDao实例
- @Autowired
- public void setUserDao( @Qualifier ( "userDao" ) UserDao userDao) {
- this .userDao = userDao;
- }
@Autowired public void setUserDao(@Qualifier("userDao") UserDao userDao) { this.userDao = userDao; }
这样,Spring会找到id为userDao的bean进行装配。
2. 可能不存在UserDao实例
- @Autowired (required = false )
- public void setUserDao(UserDao userDao) {
- this .userDao = userDao;
- }
@Autowired(required = false) public void setUserDao(UserDao userDao) { this.userDao = userDao; }
1.5. @Resource(JSR-250标准注解,推荐使用它来代替Spring专有的@Autowired注解)
Spring
不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource、@PostConstruct
以及@PreDestroy。
@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按
byName自动注入罢了。@Resource有两个属性是比较重要的,分别是name和type,Spring将@Resource注解的name属性
解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使
用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
@Resource装配顺序
- 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
- 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
- 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
- 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配(见2);如果没有匹配,则回退为一个原始类型 (UserDao)进行匹配,如果匹配则自动装配;
1.6. @PostConstruct(JSR-250)
在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行(注:Bean初始化包括,实例化
Bean,并装配Bean的属性(依赖注入))。
它的一个典型的应用场景是,当你需要往Bean里注入一个其父类中定义的属性,而你又无法复写父类的属性或属性的setter方法时,如:
- public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
- private SessionFactory mySessionFacotry;
- @Resource
- public void setMySessionFacotry(SessionFactory sessionFacotry) {
- this .mySessionFacotry = sessionFacotry;
- }
- @PostConstruct
- public void injectSessionFactory() {
- super .setSessionFactory(mySessionFacotry);
- }
- ...
- }
public class UserDaoImpl extends HibernateDaoSupport implements UserDao { private SessionFactory mySessionFacotry; @Resource public void setMySessionFacotry(SessionFactory sessionFacotry) { this.mySessionFacotry = sessionFacotry; } @PostConstruct public void injectSessionFactory() { super.setSessionFactory(mySessionFacotry); } ... }
这里通过@PostConstruct,为UserDaoImpl的父类里定义的一个sessionFactory私有属性,注入了我们自己定义
的sessionFactory(父类的setSessionFactory方法为final,不可复写),之后我们就可以通过调用
super.getSessionFactory()来访问该属性了。
1.7. @PreDestroy(JSR-250)
在方法上加上注解@PreDestroy,这个方法就会在Bean初始化之后被Spring容器执行。由于我们当前还没有需要用到它的场景,这里
不不去演示。其用法同@PostConstruct。
1.8. 使用<context:annotation-config />简化配置
Spring2.1添加了一个新的context的Schema命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配
置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。
AutowiredAnnotationBeanPostProcessor和
CommonAnnotationBeanPostProcessor就是处理这些注释元数据的处理器。但是直接在Spring配置文件中定义这些
Bean显得比较笨拙。Spring为我们提供了一种方便的注册这些BeanPostProcessor的方式,这就
是<context:annotation-config />:
- <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 />
- </beans>
<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 /> </beans>
<context:annotationconfig
/>将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、
CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor以及
RequiredAnnotationBeanPostProcessor这4个BeanPostProcessor。
2. 使用Spring注解完成Bean的定义
以上我们介绍了通过@Autowired或@Resource来实现在Bean中自动注入的功能,下面我们将介绍如何注解Bean,从而从XML
配置文件中完全移除Bean定义的配置。
2.1. @Component(不推荐使用)、@Repository、@Service、@Controller
只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了:
- @Component
- public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
- ...
- }
@Component public class UserDaoImpl extends HibernateDaoSupport implements UserDao { ... }
使用@Component注解定义的Bean,默认的名称(id)是小写开头的非限定类名。如这里定义的Bean名称就是
userDaoImpl。你也可以指定Bean的名称:
@Component("userDao")
@Component是所有受Spring管理组件的通用形式,Spring还提供了更加细化的注解形式:@Repository、
@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。目前版本(2.5)中,这些注解与
@Component的语义是一样的,完全通用,在Spring以后的版本中可能会给它们追加更多的语义。所以,我们推荐使用@Repository、
@Service、@Controller来替代@Component。
2.2. 使用<context:component-scan />让Bean定义注解工作起来
- <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 = "com.kedacom.ksoa" />
- </beans>
<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="com.kedacom.ksoa" /> </beans>
这里,所有通过<bean>元素定义Bean的配置内容已经被移除,仅需要添加一行<context:component-
scan />配置就解决所有问题了——Spring
XML配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。<context:component-scan
/>的base-package属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。
<context:component-scan
/>还允许定义过滤器将基包下的某些类纳入或排除。Spring支持以下4种类型的过滤方式:
- 过滤器类型 表达式范例 说明
- 注解 org.example.SomeAnnotation 将所有使用SomeAnnotation注解的类过滤出来
- 类名指定 org.example.SomeClass 过滤指定的类
- 正则表达式 com\.kedacom\.spring\.annotation\.web\..* 通过正则表达式过滤一些类
- AspectJ表达式 org.example..*Service+ 通过AspectJ表达式过滤一些类
以正则表达式为例,我列举一个应用实例:
- <context:component-scan base- package = "com.casheen.spring.annotation" >
- <context:exclude-filter type="regex" expression= "com\.casheen\.spring\.annotation\.web\..*" />
- </context:component-scan>
<context:component-scan base-package="com.casheen.spring.annotation"> <context:exclude-filter type="regex" expression="com\.casheen\.spring\.annotation\.web\..*" /> </context:component-scan>
值得注意的是<context:component-scan
/>配置项不但启用了对类包进行扫描以实施注释驱动Bean定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了
AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor),
因此当使用<context:component-scan />后,就可以将<context:annotation-config
/>移除了。
2.3. 使用@Scope来定义Bean的作用范围
在使用XML定义Bean时,我们可能还需要通过bean的scope属性来定义一个Bean的作用范围,我们同样可以通过@Scope注解来完
成这项工作:
- @Scope ( "session" )
- @Component ()
- public class UserSessionBean implements Serializable {
- ...
- }
@Scope("session") @Component() public class UserSessionBean implements Serializable { ... }
3. 参考
http://kingtai168.iteye.com/blog/244002
http://www.iteye.com/topic/244153
http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config
http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-classpath-scanning
发表评论
-
求鱼不如求渔 Welcome to MICKY's HOME Spring中加载ApplicationContext.xml文件的方式【转
2013-03-08 10:43 8061.利用ClassPathXmlApplication ... -
小试Bean Validation
2012-03-18 21:56 843数据校验是任何一个应用程序都会用到的功能,无论是显示层还是持久 ... -
Hibernate-Validation的使用
2012-03-18 11:56 1413以前弄过hibernate-validation的,可今天 ... -
springMVC3 基于注解的输入验证
2012-03-18 00:51 1584在pom.xml中加入,他需要validation-api ... -
pring3.0支持restful实例
2012-03-16 11:59 1066最近在研究spring3.0以及传说中的restful,还 ... -
Spring REST
2012-03-16 11:40 1161前面介绍过Spring的MVC结合不同的view显示不同的 ... -
设计 REST 风格的 MVC 框架
2012-03-16 11:38 928简介: 传统的 JavaEE MVC 框架如 Struts ... -
Spring mvc 构造RESTful URL 详细讲解(spring 3.0 应用)
2012-03-16 11:34 2296详细讲解spring rest使用,简单例子如下: / ... -
Spring MVC REST 例子
2012-03-16 03:17 1204package com.benx; ... -
ibatis存储过程调用(转载)
2011-08-14 17:11 10671 ibatis 调用oracle函数示例 2 ... -
通通透透理解ThreadLocal
2011-02-23 18:06 708概述 我们知道Spring通过各种DAO模板类降低了开发者使 ... -
乐观锁与悲观锁
2011-02-23 17:49 841文章转自网上好像是玉米田的,忘记了锁( locking ) 业 ... -
spring 依赖注入到直接new 对象
2010-09-16 15:50 978当为遗留系统加入spring时,经典问题就是遗留系统需要引用s ... -
Spring2.0用注解实现事务管理
2010-06-03 15:50 858Spring2.0 框架的事务处理有两大类: 1 ...
相关推荐
Spring注解入门
javaSpring注解入门[参考].pdf
分析了常用的spirng标注,更浅显易懂!
使用Spring的注解方式实现AOP入门
基于SpringMVC以及Spring,Hibernate的非注解入门小demo
spring3.0mvc自学教程ppt+注解教程+注解实例+springmybatis教程+项目实例+中文api 初学(自学)着的不二法定,从入门到项目实例深入学习(浅-深)
spring2.5.6注解以及xml两个简单ioc入门示例项目,导入项目可运行。 同时带有spring-framework-2.5.6-with-docs.zip包
spring注解整合hibernate,完整代码,包含jar包,很适合入门
主要介绍Spring MVC 的使用注解来配置的使用实例
例子参考了这位地址 http://www.blogjava.net/pengo/archive/2010/07/03/325164.html 但里面的jar包与目录结构发生了变化,本mvc全注解注意看那个click的链接是一个类似rest风格的例子
随着Annotation的流行,一些主流框架都加入了对Annotation的支持。使用Annotation能够简化很多配置工作...本文将 Spring 2.5 新增的 Sping MVC 注解功能,介绍如何使用注解配置替换传统的基于 XML 的 Spring MVC 配置。
n 基础应用-常用注解使用场景介绍及入门 n 高级特性-自定义BeanNameGenerator n 高级特性-自定义TypeFilter n 高级特性-ImportSelector和ImportBeanDefinitionRegistrar的分析 n 高级特性-自定义ImportSelector n ...
学习spring注解的入门文档,详细的介绍了xml文件的每个配置,以及注解的使用
'SpringDataJPA从入门到精通'分为12章 内容包括整体认识JPA、JPA基础查询方法、定义查询方法、注解式查询方法、@Entity实例里面常用注解详解、JpaRepository扩展详解、JPA的MVC扩展REST支持、DataSource的配置、乐观...
Spring主要有两大思想,一个是IoC,另一个就是AOP,对于IoC,AOP的原理就是java的动态代理机制
基于注解的 Spring MVC 简单入门
让我们更好的了解 spring mvc 注解方面的知识 适合入门
spring mvc 注解式开发 操作简单 容易上手 学完了就能使用spring mvc
主要介绍了浅谈Spring自定义注解从入门到精通,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧