---
title: "spring注解与jsr250,330"
author: "alask2011"
date: "2012-12-04T10:29:27Z"
tags: []
categories: ["开源软件"]
slug: "spring-jsr250-330"
draft: false
lastmod: "2012-12-04T10:29:27Z"
id: 1740662
url: "https://aleywang.iteye.com/blog/1740662"
---

Spring自带部分：
	
	1.依赖注入注解部分：

		1、@Autowired：自动装配
			@Autowired默认是根据类型注入，不会使用名字，除非配置了@qualifier();
			可以用于构造器、字段、方法注入，
			使用方式如下：
				@Autowired(required=true)
				构造器、字段、方法（setter(A a)&other(A a,...)）
				(如果用 @Autowired 同时标注了多个构造函数，那么，Spring 将采用贪心算法匹配构造函数 ( 构造函数最长 ))
			注意事项：
				@Autowired默认是根据参数类型进行自动装配，且必须有一个Bean候选者注入，
				如果允许出现0个Bean候选者需要设置属性“required=false”，
				“required”属性含义和@Required一样，只是@Required只适用于基于XML配置的setter注入方式
		
		2、@Required：依赖检查
			@Required只能放置在setter方法上，且通过XML配置的setter注入
			使用方法：
				public class TestBean {
					private String message;
					@Required
					public void setMessage(String message) {
						this.message = message;
					}
					public String getMessage() {
						return message;
					}
				}
				beans-xml:
				<bean id="testBean" class="xx.TestBean">
				<property name="message" ref="message"/> <!--setter注入-->
				</bean>
				<bean id="message" class="java.lang.String">
					<constructor-arg index="0" value="hello"/><!--构造赋值-->
				</bean>
			注意事项：
				配合xml的setter注入方式一起使用。
				
		3、@Value：注入SpEL表达式；
			1、可以在类字段上使用该注解：
				@Value(value = "#{message}")
				private String message;

			2、可以放置在带@Autowired注解的方法的参数上：
				@Autowired
				public void initMessage(@Value(value = "#{ T(java.lang.Math).random() * 100.0 }") String message) {
					this.message = message;
				}
			 
			3、还可以放置在带@Autowired注解的构造器的参数上：
				 @Autowired 
				 private xx(@Value(value = "#{message}#{message}") String message) {  
					 this.message = message;  
				 }
		4、@Qualifier：限定描述符，用于细粒度选择候选者；
				使用方法：
					结合@Autowired 一起使用
					
					
			 （1）、根据基于XML配置中的<qualifier>标签指定的名字进行注入，使用如下方式指定名称

					<bean id="X" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
						<qualifier  type="org.springframework.beans.factory.annotation.Qualifier"  value="限定标识符"/>
					</bean>
					class X{
					  public void initDataSource(@Qualifier("限定标识符") DataSource dataSource) {   
						   this.dataSource = dataSource;   
						}   
					}
	
					使用<qualifier>标签指定的限定标识符只能被@Qualifier使用，不能作为Bean的标识符，
					如“ctx.getBean("限定标识符")”是获取不到Bean的。

			（2）、缺省的根据Bean名字注入：最基本方式，是在Bean上没有指定<qualifier>标签时一种容错机制，即缺省情况下使用Bean标识符注入，但如果你指定了<qualifier>标签将不会发生容错。
				默认情况下（没指定<qualifier>标签）@Qualifier的value属性将匹配Bean 标识符。


			（3）、扩展@Qualifier限定描述符注解部分（有兴趣请自己深入）：
				定义：
				@Target({ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER})
				@Retention(RetentionPolicy.RUNTIME)
				@Qualifier
				public @interface DataSourceType {
					String ip();      //指定ip,用于多数据源情况
					DataBase database();//指定数据库类型
				}
			
				使用：
				@Autowired
				public void initDataSource(
						@DataSourceType(ip="localhost", database=DataBase.MYSQL)
						DataSource mysqlDataSource,
						@DataSourceType(ip="localhost", database=DataBase.ORACLE)
						DataSource oracleDataSource) {
					this.mysqlDataSource = mysqlDataSource;
					this.oracleDataSource = oracleDataSource;
				}

				
	2.初始化bean部分：
	
		1，@Component
			@Component是一个一般的注释。用于一般的类。
			@Repository,@Service,@Controller是特殊的预定义的注释。 
		2，@Repository
			用于数据访问组件，即Dao
			@Repository ("xxDao")
	  
		3，@Service
			用于业务逻辑组件。
			@Service("xxService")

		4，@Controller
			用于控制类组件。即Action
			@Controller
			public class MyController{...} 

	 
		5，配合的注解@Scope("prototype")，@Scope("session")使用
	
		
		
		
JSR-250注解:

		1、@Resource：自动装配
			默认byName，找不到会退而使用 byType 继续匹配。
			使用方法：    
				@Resource(name = "标识符",)
				字段或setter方法
			@Resource装配顺序
			　　1. 如果同时指定了name和type，则从Spring上下文中找到唯一匹配的bean进行装配，找不到则抛出异常
			　　2. 如果指定了name，则从上下文中查找名称（id）匹配的bean进行装配，找不到则抛出异常
			　　3. 如果指定了type，则从上下文中找到类型匹配的唯一bean进行装配，找不到或者找到多个，都会抛出异常
			　　4. 如果既没有指定name，又没有指定type，则自动按照byName方式进行装配；如果没有匹配，则回退为一个原始类型进行匹配，如果匹配则自动装配；


			使用@Resource需要注意以下几点：
				1. @Resource注解应该只用于setter方法注入，不能提供如@Autowired多参数方法注入；
				2. @Resource在没有指定name属性的情况下首先将根据setter方法对于的字段名查找资源，如果找不到再根据类型查找；
				3. @Resource首先将从JNDI环境中查找资源，如果没找到默认再到Spring容器中查找，因此如果JNDI环境中有和Spring容器同名的资源时需要注意。

		2、@PostConstruct和PreDestroy：通过注解指定初始化和销毁方法定义
				相当于xml里面配置的init-method，destory-method属性
				但具有更高优先级，即注解方式的初始化和销毁方法将先执行。
	
	
JSR-330注解:

		1、@Inject：等价于默认的@Autowired，只是没有required属性；

        2、@Named：指定Bean名字，对应于Spring自带@Qualifier中的缺省的根据Bean名字注入情况；

        3、@Qualifier：只对应于Spring自带@Qualifier中的扩展@Qualifier限定描述符注解，即只能扩展使用，没有value属性。


	
JPA注解:

		1.用于注入EntityManagerFactory和EntityManager。


	
	
	
	
在spring中一些常见的省略的配置：
	1. <context:annotation-config />
		作用是隐式地向 Spring 容器注册 
		CommonAnnotationBeanPostProcessor、
		AutowiredAnnotationBeanPostProcessor、
		PersistenceAnnotationBeanPostProcessor、
		RequiredAnnotationBeanPostProcessor 这4个BeanPostProcessor.

		例如:

		如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor。

		如果想使用@PersistenceContext注解，就必须声明PersistenceAnnotationBeanPostProcessor的Bean。

		如果你想使用@Autowired注解，那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。
		传统声明方式如下：<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/> 

		如果想使用 @Required的注解，就必须声明RequiredAnnotationBeanPostProcessor的Bean。同样，传统的声明方式如下：
		<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
	
	
	
	2.<context:spring-configured/>

		Spring 可以为IOC容器里的bean进行依赖注入，但如果某些类，没有配置在IOC里，比如一些Domain Object，是否也可以依赖注入？答案是肯定的。
		以User 为例，该User并没有配置在IOC里，但我想对其里面的一个UserDao进行依赖注入，其代码如下：
		@Configurable(autowire = Autowire.BY_NAME, dependencyCheck = false)
		public class User {
			  private String UserName;
			  ....
			  private  UserDao userDao;  

			  ...  

			  @Autowired/@Bean
			  public void setUserDao〔UserDao userDao〕{
					 this.userDao=userDao.
			  }
		}
		然后再在XML文件里加上 就可以了。
		主要是通过Spring管理AnnotationBeanConfigurerAspect切面， 具体的工作由该切面完成。

	3.<context:property-placeholder location="classpath:config/mybatis/jdbc.properties,classpath:config/others/config.properties" />
		
		以前使用的方式：
		<!-- PropertyPlaceholderConfigurer,用于spring ${placeholder}的解析 -->
		<bean id="propertyConfigurer"
			class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
			<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
			<property name="properties">
				<bean class="org.springframework.beans.factory.config.PropertiesFactoryBean">
					<property name="ignoreResourceNotFound" value="true" />
					<property name="locations">
							<list>
								<!-- 标准配置 -->
								<value>classpath:config/others/config.properties</value>
								<value>classpath:config/mybatis/jdbc.properties</value>
							</list>
					</property>
				</bean>
			</property>
		</bean>
	
	
	4.<context:component-scan base-package="example" use-default-filters="false">
		<context:include-filter type="aspectj" expression="example..Stub*"/>
		<context:exclude-filter type="annotation" expression="example.Mock"/>
	</context:component-scan> 
	
	
	
spring mvc 部分省略的配置：
	mvc:annotation-driven
	mvc:interceptors
	mvc:view-controller
	mvc:resources
	mvc:default-servlet-handler

	
	
//以上资料供不时之需