1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Spring XML配置文件详解

Spring XML配置文件详解

时间:2022-07-29 22:48:34

相关推荐

Spring XML配置文件详解

​ 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="/2001/XMLSchema-instance"xmlns:tx="/schema/tx"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans.xsd/schema/context /schema/context/spring-context.xsd/schema/aop /schema/aop/spring-aop.xsd/schema/tx /schema/tx/spring-tx.xsd"><!-- 注解包扫描 --><context:component-scan base-package="com.test.fx.service"></context:component-scan><!-- 引入DB配置文件 --><context:property-placeholder location="classpath:oracleDriver.properties"/><!-- 配置数据源 --><bean id="dataSource" class="mons.dbcp.BasicDataSource"><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="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><property name="mapperLocations" value="classpath:com/baizhi/fx/dao/*DaoImpl.xml"></property></bean><!-- 扫描Mapper文件并生成dao对象 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property><property name="basePackage" value="com.test.fx.dao"></property></bean><!-- 配置事务管理器 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 事务管理器注解 --><tx:annotation-driven transaction-manager="transactionManager"/></beans>

二、配置文件详解

上面给出了Spring最基本的配置文件示例,下面就其标签元素进行详细说明
1.XML结构体概述

这是一个最基本的Spring XML配置文件结构体,这些格式基本都是固定的,可以直接复用

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans" <!-- 默认bean命名空间 -->xmlns:xsi="/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.0.xsd/schema/aop/schema/aop/spring-aop-4.0.xsd/schema/context/schema/context/spring-context-4.0.xsd "></beans>

2.<Bean>标签

<!-- 一个最基本的bean标签 --><bean id="bean名称" class="bean的类全名(类全限定路径)" scope="作用域">

上面bean配置了3条最常见的属性,实际上bean的属性有以下内容:

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{@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("TestInitializingBean "); } }

<!-- 配置文件 --><bean id="testInitializingBean" class="com.TestInitializingBean" ></bean>

// 测试类如下public class Main {public static void main(String[] args){ApplicationContext context = new FileSystemXmlApplicationContext("/src/main/java/com/beans.xml");}}// 打印结果为:TestInitializingBean

如果在配置文件中指明了bean的init-method方法,则不用实现InitializingBean接口。示例如下

public class TestInitMethod{public void testInit(){System.out.println("test init-method"); }}

<bean id="testInitMethod" class="com.TestInitMethod" init-method="testInit"></bean>

public class Main {public static void main(String[] args){ClassPathXmlApplicationContext context1 = new ClassPathXmlApplicationContext("spring.xml");}}// 打印结果为:test init-method

destroy-method属性:

与之init初始化方法类似的是,此属性替代的是DisposableBean接口中的destroy()方法当bean的作用域scope = "prototype"时,该属性将失效,因为在spring中,如果一个bean为多例的,那么该bean被创建后,spring将不再去管理了

关于abstract和praent属性:

// 这里有一个类叫做XiaoMingpublic class XiaoMing{private String id;private String loginName;private String loginPwd;private String sex;}// 又有另一个类叫XiaoHongpublic 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="com.test.demo.XiaoMing" parent="loginAbstract"><property name="id" value="001" /><property name="sex" value="man" /></bean><bean id="xiaoHong" class="com.test.demo.XiaoHong" 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="com.factory.demo.CarFactory"/><!-- 由工厂创建该类时,可以省略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="com.bean.demo.CarFactory" 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="com.bean.demo.CarFactory" 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="mons.dbcp.BasicDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver" /><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="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource"><ref local="dataSource"/><!-- <ref bean="dataSource">--></property><property name="configLocation" value="classpath:mybatis-config.xml"/></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="com.test.CurdServiceImpl(匹配的类型)" implement-interface="com.test.CurdService(实现的接口)" default-impl="com.test.CurdServiceImpl(默认实现类)"/></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="mons.dbcp.BasicDataSource"><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="org.springframework.jdbc.datasource.DataSourceTransactionManager"><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(* com.sqp.spring.service.*.*(..))"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="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/><!-- 使用 @Required注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean --><bean class="org.springframework.beans.factory.annotation.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="com.myapp" />

这个配置隐式注册了多个对注解进行解析处理的处理器,包括<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="com.sparta.trans" use-default-filters="false"><context:include-filter type="annotation"expression="org.springframework.stereotype.Controller"/></context:component-scan>

**<context:property-placeholder>**配置文件处理

用来处理用一个proerties文件里面的内容来替换spring配置文件中的${}内容,例如:

<!-- 引入DB配置文件 --><context:property-placeholder location="classpath:oracleDriver.properties"/><!-- 配置数据源 --><bean id="dataSource" class="mons.dbcp.BasicDataSource"><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>

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、System.getProperty(),System.getenv(),否则正好反过来;NEVER:只查找properties-ref、location;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。