Spring XML 配置

Spring XML 配置是 Spring Framework 的传统配置方式,通过 XML 文件定义 Bean、依赖注入、AOP 等核心功能。以下是详细的 Spring XML 配置解析:


一、基础配置

1. XML 配置文件结构
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.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Bean 定义 -->
</beans>
2. Bean 定义

使用 <bean> 标签定义对象,核心属性:

  • id:在同一个 ApplicationContext 中唯一标识符(可选,若不指定可用 name)。
  • class:类的全限定名(必需)。
  • scope:Bean 的作用域(默认 singleton)。
  • init-method:初始化方法(如 init())。
  • destroy-method:销毁方法(如 cleanup())。
xml 复制代码
<bean id="userService" class="com.example.UserService" scope="prototype" init-method="init" destroy-method="destroy"/>

二、依赖注入(DI)

1. Setter 注入

通过 <property> 标签注入属性:

xml 复制代码
<bean id="user" class="com.example.User">
    <property name="name" value="Alice"/>
    <property name="age" value="25"/>
    <property name="address" ref="addressBean"/>
</bean>

<bean id="addressBean" class="com.example.Address"/>
2. 构造器注入

通过 <constructor-arg> 标签注入构造参数:

xml 复制代码
<bean id="user" class="com.example.User">
    <constructor-arg value="Alice" index="0"/>
    <constructor-arg value="25" type="int" index="1"/>
    <constructor-arg ref="addressBean"/>
</bean>
3. 引用其他 Bean

使用 ref 属性引用已定义的 Bean:

xml 复制代码
<property name="dependency" ref="otherBean"/>
4. 内联 Bean

直接在属性中定义匿名 Bean:

xml 复制代码
<property name="dateFormatter">
    <bean class="java.text.SimpleDateFormat">
        <constructor-arg value="yyyy-MM-dd"/>
    </bean>
</property>

三、高级配置

1. 作用域(Scope)
  • singleton:默认,容器内唯一实例。
  • prototype:每次请求生成新实例。
  • request/session:Web 应用中与请求/会话绑定。
xml 复制代码
<bean id="cart" class="com.example.Cart" scope="session"/>
2. 生命周期回调

通过 init-methoddestroy-method 定义初始化和销毁逻辑:

java 复制代码
public class Database {
    public void connect() { /* 初始化连接 */ }
    public void disconnect() { /* 关闭连接 */ }
}
xml 复制代码
<bean id="database" class="com.example.Database" init-method="connect" destroy-method="disconnect"/>
3. 自动装配(Autowire)

通过 autowire 属性自动注入依赖:

  • byName:按属性名匹配 Bean。
  • byType:按类型匹配 Bean(可能冲突)。
  • default:继承父容器的配置。
xml 复制代码
<bean id="orderService" class="com.example.OrderService" autowire="byType"/>

四、AOP 配置

1. 定义切面

使用 <aop:config> 配置切面、通知和切入点:

xml 复制代码
<aop:config>
    <aop:aspect ref="loggingAspect">
        <!-- 定义切入点 -->
        <aop:pointcut id="serviceMethods" expression="execution(* com.example.service.*.*(..))"/>
        
        <!-- 前置通知 -->
        <aop:before pointcut-ref="serviceMethods" method="logBefore"/>
        
        <!-- 环绕通知 -->
        <aop:around pointcut-ref="serviceMethods" method="logAround"/>
    </aop:aspect>
</aop:config>

<bean id="loggingAspect" class="com.example.aspect.LoggingAspect"/>

五、其他关键配置

1. 组件扫描

结合 context 命名空间启用注解驱动:

xml 复制代码
<context:component-scan base-package="com.example"/>
2. 事务管理

配置事务通知和代理:

xml 复制代码
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:pointcut id="serviceLayer" expression="execution(* com.example.service.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceLayer"/>
</aop:config>
3. 导入外部配置

合并多个 XML 文件:

xml 复制代码
<import resource="classpath:database-config.xml"/>
<import resource="classpath:security-config.xml"/>

六、最佳实践

  1. 避免过度配置 :优先使用注解(如 @Autowired@Component)。
  2. 模块化配置:拆分 XML 文件,按功能模块组织。
  3. 结合 Java Config :使用 @Configuration 类混合配置。

七、常见问题

  1. Bean 未找到 :检查 idclass 是否正确,或是否导入了配置文件。
  2. 循环依赖:尽量使用 Setter 注入,或重构代码。
  3. 作用域冲突 :确保 singleton Bean 不依赖 prototype Bean 的状态。

八、复杂数据结构的bean配置方式

在 Spring XML 配置中,可以通过特定标签定义 ListSetMapProperties 类型的集合,并将它们注入到 Bean 的属性中。以下是详细语法和示例:


1. 定义 List

使用 <list> 标签定义有序且允许重复的集合。
适用场景 :注入 List<String>List<Bean> 等。

语法示例
xml 复制代码
<bean id="exampleBean" class="com.example.ExampleBean">
    <property name="stringList">
        <list>
            <value>Hello</value>
            <value>World</value>
            <ref bean="anotherBean"/> <!-- 引用其他 Bean -->
        </list>
    </property>
</bean>
对应 Java 类
java 复制代码
public class ExampleBean {
    private List<Object> stringList; // 可以是 String、Bean 或混合类型
    // Getter 和 Setter
}

2. 定义 Set

使用 <set> 标签定义无序且不允许重复的集合。
适用场景 :注入 Set<Integer>Set<Bean> 等。

语法示例
xml 复制代码
<bean id="exampleBean" class="com.example.ExampleBean">
    <property name="numberSet">
        <set>
            <value>1</value>
            <value>2</value>
            <value>2</value> <!-- 重复值会被忽略 -->
        </set>
    </property>
</bean>
对应 Java 类
java 复制代码
public class ExampleBean {
    private Set<Integer> numberSet;
    // Getter 和 Setter
}

3. 定义 Map

使用 <map> 标签定义键值对集合,每个键值对用 <entry> 标签。
适用场景 :注入 Map<String, String>Map<String, Bean> 等。

语法示例
xml 复制代码
<bean id="exampleBean" class="com.example.ExampleBean">
    <property name="configMap">
        <map>
            <entry key="username" value="admin"/>
            <entry key="timeout" value="30"/>
            <entry key="service" ref="myService"/> <!-- 引用 Bean -->
        </map>
    </property>
</bean>
对应 Java 类
java 复制代码
public class ExampleBean {
    private Map<String, Object> configMap; // 键和值可以是任意类型
    // Getter 和 Setter
}

4. 定义 Properties

使用 <props> 标签定义键值对集合,键和值必须是字符串
适用场景:注入配置信息(如数据库连接参数)。

语法示例
xml 复制代码
<bean id="databaseConfig" class="com.example.DatabaseConfig">
    <property name="connectionParams">
        <props>
            <prop key="driver">com.mysql.jdbc.Driver</prop>
            <prop key="url">jdbc:mysql://localhost:3306/mydb</prop>
            <prop key="username">root</prop>
            <prop key="password">secret</prop>
        </props>
    </property>
</bean>
对应 Java 类
java 复制代码
public class DatabaseConfig {
    private Properties connectionParams; // Properties 类型
    // Getter 和 Setter
}

5. 混合类型集合

可以在集合中混合基本类型、字符串和 Bean 引用。

示例
xml 复制代码
<bean id="complexBean" class="com.example.ComplexBean">
    <property name="mixedList">
        <list>
            <value>Text</value>
            <ref bean="mathService"/>
            <bean class="com.example.CustomObject"/>
        </list>
    </property>
</bean>

6. 注意事项

  1. 集合类型匹配

    • 确保 XML 中定义的集合类型与 Java 类中的属性类型兼容。
    • 例如:如果 Java 属性是 List<String>,则 XML 中只能包含 <value> 或字符串。
  2. 引用其他 Bean

    使用 <ref bean="..."/> 引用容器中的其他 Bean。

  3. 空集合处理

    如果集合可能为空,可以使用 <list/><map/> 定义空集合。

  4. 集合嵌套

    支持集合的嵌套,例如 List<Map<String, List<String>>>


相关推荐
.生产的驴12 分钟前
SpringBoot 封装统一API返回格式对象 标准化开发 请求封装 统一格式处理
java·数据库·spring boot·后端·spring·eclipse·maven
猿周LV19 分钟前
JMeter 安装及使用 [软件测试工具]
java·测试工具·jmeter·单元测试·压力测试
晨集21 分钟前
Uni-App 多端电子合同开源项目介绍
java·spring boot·uni-app·电子合同
时间之城24 分钟前
笔记:记一次使用EasyExcel重写convertToExcelData方法无法读取@ExcelDictFormat注解的问题(已解决)
java·spring boot·笔记·spring·excel
椰羊~王小美31 分钟前
LeetCode -- Flora -- edit 2025-04-25
java·开发语言
凯酱39 分钟前
MyBatis-Plus分页插件的使用
java·tomcat·mybatis
程序员总部1 小时前
如何在IDEA中高效使用Test注解进行单元测试?
java·单元测试·intellij-idea
oioihoii1 小时前
C++23中if consteval / if not consteval (P1938R3) 详解
java·数据库·c++23
佳腾_1 小时前
【Web应用服务器_Tomcat】一、Tomcat基础与核心功能详解
java·前端·中间件·tomcat·web应用服务器
异常君1 小时前
线程池隐患解析:为何阿里巴巴拒绝 Executors
java·后端·代码规范