当前位置: 首页 > ds >正文

Spring XML 配置

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


一、基础配置

1. 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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://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())。
<bean id="userService" class="com.example.UserService" scope="prototype" init-method="init" destroy-method="destroy"/>

二、依赖注入(DI)

1. Setter 注入

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

<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> 标签注入构造参数:

<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:

<property name="dependency" ref="otherBean"/>
4. 内联 Bean

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

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

三、高级配置

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

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

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

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

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

四、AOP 配置

1. 定义切面

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

<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 命名空间启用注解驱动:

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

配置事务通知和代理:

<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 文件:

<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> 等。

语法示例
<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 类
public class ExampleBean {private List<Object> stringList; // 可以是 String、Bean 或混合类型// Getter 和 Setter
}

2. 定义 Set

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

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

3. 定义 Map

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

语法示例
<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 类
public class ExampleBean {private Map<String, Object> configMap; // 键和值可以是任意类型// Getter 和 Setter
}

4. 定义 Properties

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

语法示例
<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 类
public class DatabaseConfig {private Properties connectionParams; // Properties 类型// Getter 和 Setter
}

5. 混合类型集合

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

示例
<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>>>


http://www.xdnf.cn/news/1147.html

相关文章:

  • Kotlin集合全解析:List和Map高频操作手册
  • LM35 温度传感器介绍
  • 学习前端(前端技术更新较快,需持续关注技术更新)
  • 深入探讨:如何完美完成标签分类任务(数据治理中分类分级的分类思考)
  • 短信验证码安全实战:三网API+多语言适配开发指南
  • 网络原理 - 4(TCP - 1)
  • 短视频+直播商城系统源码全解析:音视频流、商品组件逻辑剖析
  • 【Linux】46.网络基础(3.3)
  • 何东山团队提到的“真正真空”(zero-point-free vacuum)
  • 3.1goweb框架gin下
  • 中文通用embedding:BGE
  • 使用Spark-TTS-0.5B模型,文本合成语音
  • HCIP(综合实验2)
  • mockMvc构建web单元测试学习笔记
  • Unity-GC详解
  • 面试网络基础知识 — IP地址
  • PyTorch 分布式 DistributedDataParallel (DDP)
  • Nordic外设GPIO[nrfx_gpiote_in_init函数报NRFX_ERROR_NO_MEM并且fatal error]
  • 门控循环单元(GRU)
  • LX10-MDK的使用技巧
  • 【Spring Boot基础】MyBatis的基础操作:增删查改、列名和属性名匹配 -- XML实现
  • 【Java面试笔记:基础】7.int和Integer有什么区别?
  • kubernetes》》k8s》》删除命名空间
  • Spring中配置 Bean 的两种方式:XML 配置 和 Java 配置类
  • 18.2基于Linux的INPUT子系统实验(详细编写程序)_csdn
  • IDEA 创建Maven 工程(图文)
  • dmncdm达梦新云缓存数据库主从集群安装部署详细步骤说明
  • Redis 系列之 Key 过期策略介绍
  • 09.传输层协议 ——— TCP协议
  • kotlin的kmp编程中遇到Unresolved reference ‘java‘问题