在spring中如何在xml配置中加载properties文件

在Spring中,你可以使用PropertyPlaceholderConfigurer来加载和解析properties文件。以下是在XML配置中加载properties文件的步骤:

假设我们有一个jdbc.properties的配置文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm753as
jdbc.username=root
jdbc.password=123456

首先,在XML配置文件中引入context命名空间,如下所示:

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

然后,在XML配置文件中添加PropertyPlaceholderConfigurer bean的定义,指定要加载的properties文件路径,例如:

<context:property-placeholder location="classpath:jdbc.properties" />

最后,你可以通过${}语法在其他bean定义中使用properties文件中的属性值,例如:

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

猜你喜欢

转载自blog.csdn.net/tyxjolin/article/details/130774637