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-method
和 destroy-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"/>
六、最佳实践
- 避免过度配置 :优先使用注解(如
@Autowired
、@Component
)。 - 模块化配置:拆分 XML 文件,按功能模块组织。
- 结合 Java Config :使用
@Configuration
类混合配置。
七、常见问题
- Bean 未找到 :检查
id
或class
是否正确,或是否导入了配置文件。 - 循环依赖:尽量使用 Setter 注入,或重构代码。
- 作用域冲突 :确保
singleton
Bean 不依赖prototype
Bean 的状态。
八、复杂数据结构的bean配置方式
在 Spring XML 配置中,可以通过特定标签定义 List
、Set
、Map
和 Properties
类型的集合,并将它们注入到 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. 注意事项
-
集合类型匹配
- 确保 XML 中定义的集合类型与 Java 类中的属性类型兼容。
- 例如:如果 Java 属性是
List<String>
,则 XML 中只能包含<value>
或字符串。
-
引用其他 Bean
使用
<ref bean="..."/>
引用容器中的其他 Bean。 -
空集合处理
如果集合可能为空,可以使用
<list/>
或<map/>
定义空集合。 -
集合嵌套
支持集合的嵌套,例如
List<Map<String, List<String>>>
。