spring配置文件是用于指导Spring工厂进行Bean生产、依赖关系注入(装配)及Bean实例分发的"图纸"。Spring框架的配置文件是基于xml的,Spring强大的功能依赖于类型繁多的配置项,这些配置项纷繁复杂难以记忆,下面将常用的配置项示例记录下来,以备后续查看使用。
一、Spring配置文件示例
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans"
xmlns:context="/schema/context"
xmlns:aop="/schema/aop"
xmlns:xsi="http:///2001/XMLSchema-instance"
xmlns:tx="/schema/tx"
xsi:schemaLocation="/schema/beans /schema/beans/
/schema/context /schema/context/
/schema/aop /schema/aop/
/schema/tx /schema/tx/">
<!-- 注解包扫描 -->
<context:component-scan base-package=""></context:component-scan>
<!-- 引入DB配置文件 -->
<context:property-placeholder location="classpath:"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="">
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${name}"></property>
<property name="password" value="${password}"></property>
</bean>
<!-- 创建SqlSessionFactory -->
<bean id="sqlSessionFactory" class="">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:com/baizhi/fx/dao/*"></property>
</bean>
<!-- 扫描Mapper文件并生成dao对象 -->
<bean class="">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value=""></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事务管理器注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
二、配置文件详解
- 上面给出了Spring最基本的配置文件示例,下面就其标签元素进行详细说明
结构体概述
这是一个最基本的Spring XML配置文件结构体,这些格式基本都是固定的,可以直接复用
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="/schema/beans" <!-- 默认bean命名空间 -->
xmlns:xsi="http:///2001/XMLSchema-instance" <!-- xml约束命名空间定义 -->
xmlns:aop="/schema/aop"<!-- AOP命名空间的scheme约束 -->
xmlns:context="/schema/context" <!-- context命名空间的scheme约束 -->
xsi:schemaLocation=" <!-- 上面各个scheme的location信息(网络地址) -->
/schema/beans
/schema/beans/spring-beans-4.
/schema/aop
/schema/aop/spring-aop-4.
/schema/context
/schema/context/spring-context-4. ">
</beans>
2.<Bean>标签
<!-- 一个最基本的bean标签 -->
<bean id="bean名称" class="bean的类全名(类全限定路径)" scope="作用域">
上面bean配置了3条最常见的属性,实际上bean的属性有以下内容:
属性 | 说明 |
---|---|
id | bean的名称,可以随便起名但在spring定义中,一般为类名的驼峰命名。例如<bean id=“userServiceImpl”> |
class | bean的完全限定名,就是类的全路径名。<bean class=“”> |
scope | bean的作用域,或者叫声明周期。可选值有singleton(单例),prototype(多例,又叫原型),request,session,global session |
lazy-init | lazy-init 属性表明了bean是否为延迟加载。false为立即加载,表示在spring启动时,立刻进行实例化。为true时将不会在ApplicationContext启动时提前被实例化,而是第一次向容器通过getBean索取bean时实例化才会加载。 |
init-method | 用于在bean初始化时指定执行方法。只有一个类完整的实例被创建出来后,才能走初始化方法 |
destroy-method | 用于容器在销毁bean之前调用的方法。注意spring容器在销毁bean时会先执行对应的destroy方法后销毁该bean |
abstract | 是否为抽象Bean,spring对于抽象bean不产生实例,主要用于继承 |
parent | 父Bean的名称,会继承父Bean的属性,与Java的Class无任何关系,也就是说定义了一个抽象类,这个抽象类被作为父类,其他子类可以继承父类的属性。这个父类在spring的配置文件中定义时,无需指定class属性 |
factory-bean | 创建该bean时使用的工厂类(名字) |
factory-method | 要调用的工厂类方法 |
depends-on | 依赖对象,这个Bean在初始化时依赖的对象,这个对象会在这个Bean初始化之前创建。 |
dependency-check | 依赖检查它用来确保Bean组件通过JavaBean描述的所以依赖关系都得到满足。在与自动装配功能一起使用时,它特别有用。可选值:none(不进行依赖检查),objects(只做对象间依赖的检查),simple(只做原始类型和String类型依赖的检查),all(对所有类型的依赖进行检查。它包括了前面的objects和simple) |
autowire | 自动装配,它定义了Bean的自动装载方式。 可选值:no(不使用自动装配功能),byName(通过Bean的属性名实现自动装配),byType(通过Bean的类型实现自动装配),constructor(构造函数的参数的自动组装),autodetect通过bean类的自省机制(introspection)来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器,那么将使用byType方式 |
-
lazy-init属性需要注意的是:
-
如果一个设置了立即加载的bean1,引用了一个延时加载的bean2,那么bean1在容器启动时被实例化,而bean2由于被bean1引用,所以也被实例化,这种情况也符合延时加载的bean在第一次调用时才被实例化的规则。
-
在容器层次中通过在<beans/>元素上使用’default-lazy-init’属性来控制延时初始化也是可能的。如下面配置:
<beans default-lazy-init="true"><!-- no beans will be eagerly pre-instantiated... --></beans>
-
如果一个bean的scope属性为scope="pototype"时,即使设置了lazy-init=“false”,容器启动时不实例化bean,而是调用getBean方法实例化的
-
-
init-method属性说明:
-
此属性用于替代的是 InitializingBean接口。InitializingBean接口为bean提供了初始化方法的方式,它只有afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候会执行该方法
// 示例 import org.springframework.beans.factory.InitializingBean; public class TestInitializingBean implements InitializingBean{ @Override public void afterPropertiesSet() throws Exception { System.out.println("TestInitializingBean "); } }
<!-- 配置文件 --> <bean id="testInitializingBean" class="" ></bean>
// 测试类如下 public class Main { public static void main(String[] args){ ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/java/com/"); } } // 打印结果为:TestInitializingBean
-
如果在配置文件中指明了bean的init-method方法,则不用实现InitializingBean接口。示例如下
public class TestInitMethod{ public void testInit(){ System.out.println("test init-method"); } }
<bean id="testInitMethod" class="" init-method="testInit"></bean>
public class Main { public static void main(String[] args){ ClassPathXmlApplicationContext context1 = new ClassPathXmlApplicationContext(""); } } // 打印结果为:test init-method
-
-
destroy-method属性:
- 与之init初始化方法类似的是,此属性替代的是DisposableBean接口中的destroy()方法
- 当bean的作用域scope = "prototype"时,该属性将失效,因为在spring中,如果一个bean为多例的,那么该bean被创建后,spring将不再去管理了
-
关于abstract和praent属性:
// 这里有一个类叫做XiaoMing public class XiaoMing{ private String id; private String loginName; private String loginPwd; private String sex; } // 又有另一个类叫XiaoHong public class XiaoHong{ private String id; private String loginName; private String loginPwd; private String sex; }
此时,我们发现,这两个类有公用的字段属性,此后不管叫小刚,李四,王五也好,他们都会有共同的属性
,假设他们拥有同一个登录帐号,那么我们可以将登录字段属性设置为一个抽象类,其他子类可以继承
<bean id="loginAbstract" abstract="true"> <property name="loginName" value="admin"/> <property name="loginPwd" value="admin"/> </bean> <!-- 其他子类继承了父类中的通用属性 --> <bean id="xiaoMing" class="" parent="loginAbstract"> <property name="id" value="001" /> <property name="sex" value="man" /> </bean> <bean id="xiaoHong" class="" parent="loginAbstract"> <property name="id" value="002" /> <property name="sex" value="woman" /> </bean>
-
factory-bean & factory-method说明
这两个属性可以同时出现,也可以只指定factory-method,下面进行详细说明。
-
情况一:同时使用factory-bean 和 factory-method
// 汽车生产工厂类 public class CarFactory { // 非静态方法 public Car createCar(){ Car car = new Car(); car.setBrand("BMW"); return car; } }
<!-- 配置文件中调用 --> <!-- 工厂方法--> <bean id="carFactory" class=""/> <!-- 由工厂创建该类时,可以省略class属性 --> <bean id="car1" factory-bean="carFactory" factory-method="createCar"> </bean>
我们在一个bean 元素上同时配置 factory-bean 和 factory-method, 那么意思就是说, 这个bean 的创建就使用工厂模式,即由CarFactory工厂类创建car对象。factory-method属性指向了工厂类中的具体产生car对象的方法。此处的方法必须是非静态的(如果是静态的则会抛出异常)。至于原因你也一定能想到,static方法可以直接通过类调用而无需实例化,何必再去多此一举实例化工厂类呢
-
情况二:只配置了factory-method属性
public class CarFactory { // 静态方法 public static Car createStaticCar(){ Car car = new Car(); return car; } }
<!-- 指定该bean的class类型为该bean的工厂类 --> <bean id="car2" class="" factory-method="createStaticCar"></bean>
这里该bean的class类型为产生该bean的工厂类,factory-method指向该工厂类的非静态方法。
另外工厂方法是可以有参数的,如果有参数,那么我们可以通过 constructor-arg 进行配置,原理跟 普通的 构造方法注入是一样的
public class CarFactory { // 静态方法 public static Car createStaticCar(String brand){ Car car = new Car(); car.setBrand(brand); return car; } }
<bean id="car2" class="" factory-method="createStaticCar"> <constructor-arg name="brand" value="GTR" /> </bean>
-
-
ref引用属性
用于指定属性值为spring容器中的其它bean.两个基本属性是local和bean
local:如果一个bean与被参考引用的bean在同一个xml 文件中而且被引用参考的bean是用id来命名的,那么就可以使用ref的local属性。这样会让项目里解析器更早的在xml文档解析时,验证bean的id
**Bean:**用ref元素的bean属性指定被参考引用的bean是spring中最常见的形式,它允许指向的bean可以在同一个xml,也可以不在同一个xml中。bean属性的值可以与被参考引用的bean的id属性相同,也可以与被参考引用的bean的属性不相同
<bean id="dataSource" class=""> <property name="driverClassName" value="" /> <property name="url" value="jdbc:mysql://localhost:3306/db_ssm" /> <property name="username" value="hc" /> <property name="password" value="123456" /> </bean> <bean id="sqlSessionFactoryBean" class=""> <property name="dataSource"> <ref local="dataSource"/> <!-- <ref bean="dataSource"> --> </property> <property name="configLocation" value="classpath:"/> </bean>
3.<aop>标签
<!-- 定义切面bean -->
<bean id="切面bean的id" class="类的全限定路径"></bean>
<!-- 目标对象 -->
<bean id="目标对象id" class="目标对象类的全限定路径"></bean>
<!-- 定义切面的配置:注解 -->
<aop:config>
<aop:aspect id="切面ID" ref="要引用的切面实例名称">
<!--定义一个切点 -->
<aop:pointcut id="切入点名称" expression="切入点表达式" />
<!-- 定义四类通知-->
<aop:before method="切面类前置通知方法名" pointcut-ref="引用的切入点名称"/>
<aop:after method="切面类后置通知方法名" pointcut-ref="引用的切入点名称"/>
<aop:after-returning method="切面类最终通知方法名" pointcut-ref="引用的切入点名称"/>
<aop:after-throwing method="切面类异常通知方法名" pointcut-ref="引用的切入点名称"/>
<!-- 定义环绕通知 -->
<aop:around method="切面类环绕通知方法名" pointcut-ref="引用的切入点名称"/>
<!--定义增强类 -->
<aop:declare-parents types-matching="(匹配的类型)"
implement-interface="(实现的接口)"
default-impl="(默认实现类)"/>
</aop:aspect>
</aop:config>
有关AOP的XML配置使用请移步本博客:
AOP XML的配置使用 /zxcbnm7089/article/details/104359598
4.各种bean的值注入
请移步本博客:
Spring Bean值注入 - 基于XML配置文件 /zxcbnm7089/article/details/104394070
5.<tx>事务标签
- xml配置格式如下
<!-- 配置事务管理器 -->
<bean id="事务管理bean id" class="类的全限定路径">
<property name="数据源属性名称" ref="引用的数据源实例名称" />
</bean>
<!-- 配置一个事务通知 -->
<tx:advice id="事务通知名称" transaction-manager="事务管理器实例名称">
<tx:attributes>
<tx:method name="方法名" read-only="是否只读" propagation="事务类型"/>
<!-- 其他所有方法,以默认事务运行 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<!-- 配置事务切入点 -->
<aop:config>
<aop:pointcut id="事务切入点id" expression="事务切入点表达式" />
<aop:advisor advice-ref="事务通知名称" ponitcut-ref="事务切入点id" />
</aop:config>
- 代码使用示例
<!-- 配置数据源 -->
<bean id="dataSource" class="">
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${name}"></property>
<property name="password" value="${password}"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务通知 -->
<!-- 使用<tx:advice>元素声明事务通知,需要指定id属性,以便AOP把通知和切入点关联起来 -->
<!-- 还需要指定transaction-manager属性,其值为Bean配置文件中事务管理器的id属性值 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 在<tx:advice>元素下声明<tx:attributes>元素,用于指定事务属性 -->
<!-- 在<tx:attributes>元素下可以使用多个<tx:method>元素指定不同方法的不同事务属性 -->
<tx:attributes>
<!-- 根据方法名指定事务的属性 -->
<tx:method name="BookShopXmlService" propagation="REQUIRED"/>
<!--方法名以get开头的事务属性 -->
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入点,以及把事务切入点和事务属性关联起来 -->
<!-- 在<aop:config>元素下,使用<aop:advisor>元素声明一个增强器,将事务通知和切入点关联起来 -->
<!-- 使用 advice-ref属性指定事务通知,用pointcut-ref属性指定切入点 -->
<aop:config>
<aop:pointcut expression="execution(* .*.*(..))"
id="txPointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
6.<context>标签
-
**<context:annotaion-config>**注解装配在默认情况下是不开启的,为了使用注解装配,我们必须在Spring配置文件中配置 <context:annotation-config/>元素。也就是说,如果我们想要使用@Autowired、@Resoure等注解时可以通过此标签配置,让Spring隐式的帮我们生成这些Bean。
<!-- 使用@Autowired注解,必须事先在Spring容器中声明AutowiredAnnotationBeanPostProcessor的Bean: --> <bean class=". AutowiredAnnotationBeanPostProcessor "/> <!-- 使用 @Required注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean --> <bean class=". RequiredAnnotationBeanPostProcessor"/> <!-- 类似地,使用@Resource、@PostConstruct、@PreDestroy等注解就必须声明 CommonAnnotationBeanPostProcessor;使用@PersistenceContext注解,就必须声明 PersistenceAnnotationBeanPostProcessor的Bean。 --> <!-- 这样的声明未免太不优雅,而Spring为我们提供了一种极为方便注册这些BeanPostProcessor的方式,即使用<context:annotation- config/>隐式地向 Spring容器注册AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor。 --> <context:annotation-config/>
-
**<context:component-scan>**组件扫描
Spring2.5为我们引入了组件自动扫描机制,它可以在类路径底下寻找标注了@Component、@Service、@Controller、@Repository注解的类,并把这些类纳入进Spring容器中管理。
<!-- base-package 指定了要扫描的包路径 --> <context:component-scan base-package="" />
这个配置隐式注册了多个对注解进行解析处理的处理器,包括
<context:annotation-config/>
该配置注册的处理器,也就是说写了<context:component-scan base-package="" />
配置,就不用写<context:annotation-config/>
配置了。另外此标签还有一个属性是use-default-filter
,默认为true这就意味着会扫描指定包下的全部的标有@Component,@Controller,@Service等等的类,并注册成bean-
另外,<context:component-scan>标签还有两个子标签,其实就是扫描时的过滤器
<context:exclude-filter> 指定的不扫描 <context:include-filter> 指定的扫描
<!-- 例如,我们只想扫描指定包下面的Controller --> <!-- 此处如果省略了use-default属性,不仅会把指定包下的Controller扫描出来,还会把带有@Service等注解的其他组件扫描出来 --> <context:component-scan base-package="" use-default-filters="false"> <context:include-filter type="annotation" expression=""/> </context:component-scan>
-
-
**<context:property-placeholder>**配置文件处理
用来处理用一个proerties文件里面的内容来替换spring配置文件中的${}内容,例如:
<!-- 引入DB配置文件 --> <context:property-placeholder location="classpath:"/> <!-- 配置数据源 --> <bean id="dataSource" class=""> <property name="driverClassName" value="${driver}"></property> <property name="url" value="${url}"></property> <property name="username" value="${name}"></property> <property name="password" value="${password}"></property> </bean>
属性 说明 location 表示引入配置文件的位置,多个之间用逗号分隔 file-encoding 指定文件编码,如GBK,UTF-8 ignore-resource-not-found 如果属性文件找不到,是否忽略,默认false,即不忽略,找不到将抛出异常 ignore-unresolvable 是否忽略解析不到的属性,如果不忽略,找不到将抛出异常 properties-ref 配置类的引用,如果在xml中声明了properties bean,那么将引用这个bean的id local-override 是否本地覆盖模式,即如果true,那么properties-ref的属性将覆盖location加载的属性 system-properties-mode 系统属性模式:ENVIRONMENT(默认),OVERRIDE,NEVER ENVIRONMENT:将使用Spring 3.1提供的PropertySourcesPlaceholderConfigurer,其他情况使用Spring 3.1之前的PropertyPlaceholderConfigurer如果是本地覆盖模式:那么查找顺序是:properties-ref、location、environment,否则正好反过来; OVERRIDE: PropertyPlaceholderConfigurer使用,因为在spring 3.1之前版本是没有Enviroment的,所以OVERRIDE是spring 3.1之前版本的Environment如果是本地覆盖模式:那么查找顺序是:properties-ref、location、(),(),否则正好反过来; NEVER:只查找properties-ref、location;