spring注解总结

一、引言

1. 没有注解之前

public class UserManagerImpl implements UserManager {  
    private UserDao userDao;  
    public void setUserDao(UserDao userDao) {  
        this.userDao = userDao;  
    }  
    ...  
}  <span style="font-size:14px;"></span>

配置文件

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

 

2. 注解诞生之后

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;  
    }  
    ...  
} 

配置文件

<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这个属性。

要使@Autowired能够工作,还需要在配置文件中加入以下代码:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> 

可以看到确实是减少了代码和配置文件中的配置。

 

二、注解详细介绍

1. @Autowired和@Resource

@Autowired注解是按类型装配依赖对象,可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它required属性为false

@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)进行匹配,如果匹配则自动装配;

2. @Qualifier(配合@Autowired使用,指定注入bean的名称)

@Autowired是根据类型进行自动装配的。在上面的例子中,如果当Spring上下文中存在不止一个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。
public class UserManagerImpl implements UserManager {  
    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;  
    ...  
} 

 

3.使用<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">  
   <span style="BACKGROUND-COLOR: #ffff00"> <context:annotation-config />  
</span></beans>  

<context:annotationconfig />将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor以及RequiredAnnotationBeanPostProcessor这4个BeanPostProcessor。

使用Spring注解完成Bean的定义 
以上我们介绍了通过@Autowired或@Resource来实现在Bean中自动注入的功能,下面我们将介绍如何注解Bean,从而从XML配置文件中完全移除Bean定义的配置。
 
在基于主机方式配置Spring的配置文件中,你可能会见到<context:annotation-config/>这样一条配置,他的作用是式地向 Spring 容器注册

AutowiredAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor

PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor  BeanPostProcessor

注册这4 BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解。

例如:

如果你想使用@Autowired注解,那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。传统声明方式如下

<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/> 

如果想使用@ Resource @ PostConstruct@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor

如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessorBean

如果想使用 @Required的注解,就必须声明RequiredAnnotationBeanPostProcessorBean。同样,传统的声明方式如下:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> 

一般来说,这些注解我们还是比较常用,尤其是Antowired的注解,在自动注入的时候更是经常使用,所以如果总是需要按照传统的方式一条一条配置显得有些繁琐和没有必要,于是spring给我们提供<context:annotation-config/>的简化配置方式,自动帮你完成声明。

   不过,呵呵,我们使用注解一般都会配置扫描包路径选项

<context:component-scan base-package=”XX.XX”/> 

    该配置项其实也包含了自动注入上述processor的功能,因此当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。
4. @Component(不推荐使用)、@Repository、@Service、@Controller 

只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了:

@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。 

 

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

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

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

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

说明: 

(1)可以为注解指明名称:例如:@Service("simpleService")如果没指明名称则默认为第一个字母小写的类名称。 

(2)如果要配置bean的作用域,只需要用@Scope进行配置。例如: @Scope("prototype")

(3)初始化方法注解:@PostConstruct

(4)销毁方法注解:  @PreDestroy 

 

 5.使用<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">  
    <span style="BACKGROUND-COLOR: #ffff00"><context:component-scan base-package="com.kedacom.ksoa" /> </span> 
</beans>  

这里,所有通过<bean>元素定义Bean的配置内容已经被移除,仅需要添加一行<context:component-scan />配置就解决所有问题了——Spring XML配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。<context:component-scan />的base-package属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。 

<context:component-scan>有一个use-default-filters属性,该属性默认为true,这就意味着会扫描指定包下的全部的标有@Service,@Component,@Repository,@Controller注解修饰的类,并注册成bean。所以如果仅仅是在配置文件中这么写

<context:component-scan base-package="tv.huan.weisp.web"/>

 user-default-filter此时为true那么会对base-package包或者子包下的所有的java类进行扫描,并把匹配的java类注册成bean。

context:component-scan节点允许有两个子节点<context:include-filter>和<context:exclude-filter>。

在Use-dafault-filters=”false”的情况下:<context:exclude-filter>表示指定的不扫描,<context:include-filter>表示指定的扫描

5.使用@Scope来定义Bean的作用范围

 在使用XML定义Bean时,我们可能还需要通过bean的scope属性来定义一个Bean的作用范围,我们同样可以通过@Scope注解来完成这项工作

@Scope("session")  
@Component()  
public class UserSessionBean implements Serializable {  
    ...  
} 

 

三、一个完整的例子

先上bean-config.xml

<?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层实现类

import org.springframework.stereotype.Repository;

/**
 * 测试Annotation
 *
 */

@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();
		
	}
}






 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值