Spring入门_bean配置与注解实现

来源:互联网 发布:手机淘宝修改差评 编辑:程序博客网 时间:2024/05/22 13:19

applicationContext.xml 文件

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
  3.     xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
  4.     xmlns:cache="http://www.springframework.org/schema/cache"  
  5.     xsi:schemaLocation="  
  6.     http://www.springframework.org/schema/context  
  7.     http://www.springframework.org/schema/context/spring-context.xsd  
  8.     http://www.springframework.org/schema/beans  
  9.     http://www.springframework.org/schema/beans/spring-beans.xsd  
  10.     http://www.springframework.org/schema/tx  
  11.     http://www.springframework.org/schema/tx/spring-tx.xsd  
  12.     http://www.springframework.org/schema/jdbc  
  13.     http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd  
  14.     http://www.springframework.org/schema/cache  
  15.     http://www.springframework.org/schema/cache/spring-cache-3.1.xsd  
  16.     http://www.springframework.org/schema/aop  
  17.     http://www.springframework.org/schema/aop/spring-aop.xsd  
  18.     http://www.springframework.org/schema/util  
  19.     http://www.springframework.org/schema/util/spring-util.xsd">  
  20.   
  21.     <!-- 自动扫描web包 ,将带有注解的类 纳入spring容器管理 ,该注解已经包含了<context:annotation-config />注解
  22. 所以后面无需使用<context:annotation-config />注解    -->  
  23.     <context:component-scan base-package="com.eduoinfo.finances.bank.web"></context:component-scan>  
  24.   

  25.  <!--自动将针对注解的处理器配置好  -->     
  26. <context:annotation-config />     
  27. <!-- 使用annotation定义事务-->  
  28. <tx:annotation-driventransaction-managertx:annotation-driventransaction-manager="transactionManager" proxy-targetclass="true"/>  
  29. <!--使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入base-package为需要扫描的包(含所有子包)-->  
  30. <context:component-scan base-packagecontext:component-scanbase-package="com" />  
  31. <beans>

  32.     <!-- 引入jdbc配置文件 -->  
  33.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  34.         <property name="locations">  
  35.             <list>  
  36.                 <value>classpath*:jdbc.properties</value>  
  37.             </list>  
  38.         </property>  
  39.     </bean>  
  40.   
  41.     <!-- dataSource 配置 -->  
  42.     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">  
  43.         <!-- 基本属性 url、user、password -->  
  44.         <property name="url" value="${jdbc.url}" />  
  45.         <property name="username" value="${jdbc.username}" />  
  46.         <property name="password" value="${jdbc.password}" />  
  47.   
  48.         <!-- 配置初始化大小、最小、最大 -->  
  49.         <property name="initialSize" value="1" />  
  50.         <property name="minIdle" value="1" />  
  51.         <property name="maxActive" value="20" />  
  52.   
  53.         <!-- 配置获取连接等待超时的时间 -->  
  54.         <property name="maxWait" value="60000" />  
  55.   
  56.         <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->  
  57.         <property name="timeBetweenEvictionRunsMillis" value="60000" />  
  58.   
  59.         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->  
  60.         <property name="minEvictableIdleTimeMillis" value="300000" />  
  61.   
  62.         <property name="validationQuery" value="SELECT 'x'" />  
  63.         <property name="testWhileIdle" value="true" />  
  64.         <property name="testOnBorrow" value="false" />  
  65.         <property name="testOnReturn" value="false" />  
  66.   
  67.         <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->  
  68.         <property name="poolPreparedStatements" value="false" />  
  69.         <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />  
  70.   
  71.         <!-- 配置监控统计拦截的filters -->  
  72.         <property name="filters" value="stat" />  
  73.     </bean>  
  74.   
  75.     <!-- mybatis文件配置,扫描所有mapper文件 -->  
  76.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:com/eduoinfo/finances/bank/web/dao/*.xml" />  
  77.   
  78.     <!-- spring与mybatis整合配置,扫描所有dao -->  
  79.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.eduoinfo.finances.bank.web.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory" />  
  80.   
  81.     <!-- 对dataSource 数据源进行事务管理 -->  
  82.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" />  
  83.   
  84.     <!-- 配置使Spring采用CGLIB代理 -->  
  85.     <aop:aspectj-autoproxy proxy-target-class="true" />  
  86.   
  87.     <!-- 启用对事务注解的支持 -->  
  88.     <tx:annotation-driven transaction-manager="transactionManager" />  
  89.   
  90.     <!-- Cache配置 -->  
  91.     <cache:annotation-driven cache-manager="cacheManager" />  
  92.     <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:ehcache.xml" />  
  93.     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehCacheManagerFactory" />  
  94.   
  95. </beans>  

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


autowire属性值有      不推荐使用

byName 根据Bean定义时的“id"属性上指定的别名与Setter名称是否一致进行自动装配

byType 根据PoJo的setXXX()方法所接受的类型判断bean定义文件是否定义有类似的类型对象进行自动装配

constructor Spring容器比对容器中的Bean实例类型及相关的构造方法上的参数类型是否符合进行自动装配

autodetect 先进行constructor自动装配,若缺省,则进行byType自动装配

no不进行自动装配   

 

depends-on

若A depends-on B 意思是实例化A之前必须先实例化B,但A不需要持有B的实例

 

abstract属性值

false默认

ture表示抽象Bean,ApplicationContext预初始化时忽略所有抽象Bean定义

 

parent   表示该Bean为子Bean,其值指向父Bean,重用父Bean已实现的依赖

 

dependency-check属性值

simple 只检查简单的属性是否完成依赖关系

objects 检查对象类型的属性是否完成依赖关系

all检查全部的属性是否完成依赖关系

none默认值,表示不检查依赖性


singleton属性值指定此Java Bean是否采用单例(Singleton)模式 

false则通过BeanFactory获取此Java Bean实例时,BeanFactory每次都将创建一个新的实例返回。

true(默认) 则在BeanFactory作用范围内,只维护此Java Bean的一个实例,代码通过BeanFactory获得此Java Bean实例的引用。

 

init-method 初始化方法,此方法将在BeanFactory创建JavaBean实例和属性set注入之后,在向应用层返回引用之前执行。一般用于一些资源的初始化工作。

 

destroy-method 销毁方法。此方法将在BeanFactory销毁的时候执行,一般用于资源释放。

 

lazy-init属性值

true 延迟加载,也就是IoC 容器将第一次被用到时才开始实例化

false默认

 

factory-bean通过实例工厂方法创建bean,class属性必须为空,factory-bean属性必须指定一个bean的名字,这个bean一定要在当前的bean工厂或者父bean工厂中,并包含工厂方法。而工厂方法本身通过factory-method属性设置。

 

factory-method 定义工厂方法,若是class属性指向工厂类,该工厂类包含的工厂方法须是static

scope属性值

 

scope可以取值: 
 * singleton:每次调用getBean的时候返回相同的实例.这个是默认,也就是单实例
 * prototype:每次调用getBean的时候返回不同的实例.这个是多实例

 

还可取值request、session、global session等(不常用)

 

具体的用法如下

<bean id="userDao" class="com.test.dao.impl.UserDAOImpl" scope="singleton"/>
 <bean id="userService" class="com.test.service.impl.UserServiceImpl" scope="prototype">
  <property name="userDao" ref="userDao"/>
 </bean>

这个怎么需要看你具体的时机...如果你的bean是无状态的.那么单实例就可以了...如果Bean是有状态的,那么你最好设置成多实例的.因为这样可以解决线程安全问题.

id: Bean的唯一标识名。它必须是合法的XML ID,在整个XML文档中唯一。 

name: 用来为id创建一个或多个别名。它可以是任意的字母符合。多个别名之间用逗号或空格分开。 

class: 用来定义类的全限定名(包名+类名)。只有子类Bean不用定义该属性


1、<context:component-scan base-package="com.eduoinfo.finances.bank.web"></context:component-scan> 作用
Spring 容器初始化的时候,会扫描 com.eduoinfo.finances.bank.web下 标有 (@Component,@Service,@Controller,@Repository) 注解的 类 纳入spring容器管理

<context:include-filter type="regex">  包括哪些文件要扫描注解,通过regex正则匹配方式
<contex:exclude-filter type="annotation"> 排除某些注解的扫描
相关的type 还有assignable(具体某一个类),aspectj,custom

在类上 ,使用以下注解,实现bean 的声明

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

@Service 用于标注业务层组件(服务层)

@Controller 用于标注控制层组件(如srping mvc的controller,struts中的action)(控制层)

@Repository 用于标注数据访问组件,即DAO组件(持久层)

示例:

@Controller
@RequestMapping(value = "/test")
public class TestController {

}

注册后bean名称为testController

或者

@Controller(“myController”)
@RequestMapping(value = "/test")
public class TestController {

}

注册后bean名称为myController


------------------------------------------------------------------------------------------------------------------

在类的成员变量上,使用以下注解,实现属性的自动装配

@Autowired : 按类 的 类型进行装配,

如果想使用按照名称(byName)来装配,可以结合@Qualifier注解一起使用。如下:

public class TestServiceImpl {@Autowired@Qualifier("userDao")private UserDao userDao; }
在找不到相关类型,会抛出异常,可以使用@Autowired(required=false)来屏蔽异常,但每个类只有一个构造器可以标记为true,也可以使用@required来代替
可以是用@AutoWired来注解解析依赖性接口,比如BeanFactory,ApplicationContext,Environment,ResourceLoader,ApplicationEventPublisher,MessageSource
@AutoWired不可以注解在自己的BeanPostProcessor和BeanFactoryPostProcessor,只能通过xml或者@bean
@AutoWired 可以注解List,Array,Map,会自动将所有相关bean加进集合,Array可以通过@order来设置顺序



@Resource (推荐) 

@Resource注解在字段上,这样就不用写setter方法了,并且这个注解是属于J2EE的,减少了与spring的耦合。 

最好是将@Resource放在setter方法上,因为这样更符合面向对象的思想,通过set、get去操作属性,而不是直接去操作属性。

@ResourceJSR-250标准注解,推荐使用它来代替Spring专有的@Autowired注解)Spring 不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource@PostConstruct以及@PreDestroy

@Resource的作用相当于@Autowired,只不过@AutowiredbyType自动注入,而@Resource默认按byName自动注入罢了。@Resource有两个属性是比较重要的,分别是nametypeSpring@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略
@Resource装配顺序

1 如果同时指定了nametype,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常

2 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常

3 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常

4 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配(见2);如果没有匹配,则回退为一个原始类型(UserDao)进行匹配,如果匹配则自动装配;

示例:

@Resource
private TestServiceImpl testServiceImpl;

public class TestServiceImpl {// 下面两种@Resource只要使用一种即可@Resource(name="userDao")private UserDao userDao; // 用于字段上@Resource(name="userDao")public void setUserDao(UserDao userDao) { // 用于属性的setter方法上this.userDao = userDao;}}


3. @PostConstructJSR-250
在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行(注:Bean初始化包括,实例化Bean,并装配Bean的属性(依赖注入))。
它的一个典型的应用场景是,当你需要往Bean里注入一个其父类中定义的属性,而你又无法复写父类的属性或属性的setter方法时,如:

cop      }   }    

  1. public class UserDaoImpl extends HibernateDaoSupport implements UserDao {     
  2.  private SessionFactory mySessionFacotry;     
  3. @Resource    
  4. public void setMySessionFacotry(SessionFactory sessionFacotry) {     
  5.     this.mySessionFacotry = sessionFacotry;     
  6.        
  7.   @PostConstruct    
  8.    public void injectSessionFactory() {     
  9.       super.setSessionFactory(mySessionFacotry);   



这里通过@PostConstruct,为UserDaoImpl的父类里定义的一个sessionFactory私有属性,注入了我们自己定义的sessionFactory(父类的setSessionFactory方法为final,不可复写),之后我们就可以通过调用super.getSessionFactory()来访问该属性了。

4.@PreDestroyJSR-250
在方法上加上注解@PreDestroy,这个方法就会在Bean初始化之后被Spring容器执行。由于我们当前还没有需要用到它的场景,这里不不去演示。其用法同@PostConstruct


5.@PreDestroyJSR-330

需要引入javax.inject包

maven引入方式:

<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>

@Inject等同与@AutoWired

@Named等同与@Component,也可以使用name属性进行特定名称的依赖注入(使用情况:一个bean有两个实例)





在bean上还可以添加其他注解

@scope  作用域,有以下5种属性

  1. singleton 表示在spring容器中的单例,通过spring容器获得该bean时总是返回唯一的实例,不用容器的bean不是同一个
  2. prototype表示每次获得bean都会生成一个新的对象
  3. request表示在一次http请求内有效(只适用于web应用)
  4. session表示在一个用户会话内有效(只适用于web应用)
  5. globalSession表示在全局会话内有效(只适用于web应用)
也可以实现某个接口以实现线程单例

@Configuration

@Bean

@Import

@DependsOn

0 0
原创粉丝点击