Spring如何引入properties外部文件

132 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第6天,点击查看活动详情

1 引入问题

为什么要引入外部属性? 以前我们在为IOC容器的bean赋值的时候,都是直接将值写在了property标签里,而这样做不是不可以。如果我们将要赋值的内容放在一个单独的文件里面的话,以后要修改要赋值的数据的话,直接去单独的文件里修改即可。

外部属性文件是怎样的? 外部文件其实是一个以properties作为文件名后缀的文件,里面的内容是以变量名=变量值的形式呈现。以后可以在spring的配置文件里通过${变量名}的方式获取变量值,从而给bean的属性名赋值。

外部文件怎么创建? 创建方很简单。在resources目录下,右键,选择new,最后选择Resource Bundle。

image-20221206204827889.png

image-20221206205003804.png

spring的配置文件如何引用properties文件引用properties文件的方法其实很简单,只需在配置文件里使用context:property-placeholder标签的location属性指定properties文件的位置即可

<!--引入jdbc.properties,之后可以通过${key}的方式访问value-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>

2 项目准备

我们引用数据库驱动的时候也需要为对应的实现类赋值,所以我们本次实验就是通过外部文件,为数据源的bean赋值

引入依赖

<!-- MySQL驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>
<!-- 数据源 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.31</version>
</dependency>

spring配置文件

<?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 https://www.springframework.org/schema/context/spring-context.xsd">

    <!--引入jdbc.properties,之后可以通过${key}的方式访问value-->
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>

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

</beans>

properties文件

properties文件的内容是变量名=变量值的形式。建议变量的命名方式最好是加个前缀,如jdbc.username。因为properties文件可能不止一个,如果你叫username,另一个文件也有username,那么就会冲突了。为了避免出现这种情况,加个前缀也好区分变量究竟是干嘛的。

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456

测试

@Test
public void testDataSource() throws SQLException {
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-datasource.xml");
    DruidDataSource dataSource = ioc.getBean(DruidDataSource.class);
    System.out.println(dataSource.getConnection());
}

image-20221206220537061.png