Spring:加载properties文件

博客介绍了在Spring中使用context命名空间加载properties文件的方法,包括开启命名空间、加载指定文件、读取属性值等。还说明了避免与系统环境变量冲突的配置方式,以及加载多个或所有properties文件的方法,最后提到在bean中用注解@Value取值。

1、开启context命名空间,总共5处标红的地方需要修改为context。

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

2、使用context命名空间,加载指定properties文件

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

properties配置文件,配置时要加jdbc,不然会和系统环境变量冲突,系统优先级高:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=root

3、使用${ }读取加载的properties文件中的属性值

说明:idea自动识别${ }加载的属性值,需要手工点击才可以查阅原始书写格式

<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>

不加载系统属性:

可通过此种方法不加载系统属性,就不会和系统属性冲突:

system-properties-mode属性:是否加载系统属性
<context:property-placeholder location="jdbc.properties" system-properties-mode="NEVER"/>

加载多个properties文件:

用逗号分隔可加载多个properties文件:

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

加载所有properties文件:

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

加载properties文件标准格式:

classpath:*.properties设置加载当前工程类路径中的所有properties文件
<context:property-placeholder location="classpath:*.properties"/>

从类路径或jar包中搜索并加载properties文件:

classpath*:*.properties设置加载当前工程类路径和当前工程所依赖的所有jar包中的所有properties文件
<context:property-placeholder location="classpath*:*.properties"/>

4、bean 中使用注解@Value("${xxx}")来取值

注意,bean必须是spring托管的@service 或@Component

@RestController
@RequestMapping("/demo_client")
public class DemoClientController {

//    @Value("${config.name}")
//    private String name;

    @Value("${my.property.key}")
    private String myPropertyName;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值