Java笔记--spring之加载属性配置文件--2021-08-17

11 篇文章 0 订阅

spring之加载属性配置文件


先定义属性配置文件,在resources文件夹下创建test.properties:

myname=hk
myage=18

然后在applicationContext.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
       https://www.springframework.org/schema/context/spring-context.xsd">
    <!--
        声明组件扫描器(component-scan),组件就是java对象
        base-package:指定注解在你的项目中的包名。
        component-scan工作方式: spring会扫描历base-package指定的包,
        把包中和子包中的所有类,找到类中的注解,按照注解的功能创建对象,或给属性属值。

        加入了component-scan标签,配置文件的变化:
            1.加入一个新的约束文件spring-context.xsd
            2.给这个新的约束文件起个命名空间的名称
    -->
    <context:component-scan base-package="com.apps.pojo07" />

    <!-- 加载属性配置文件,classpath:表示类路径 -->
    <context:property-placeholder location="classpath:test.properties" />

</beans>

然后就可以在java类中使用 ${} 来获取test.properties属性文件中的值, ${} 中的内容为properties属性文件中的key值

package com.apps.pojo07;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author hk Email:2113438464@qq.com
 * @ClassName Student
 * @Description : 实体类
 * @date 2021/6/7
 */

//省略value
@Component("myStudent")
public class Student {

    /**
     * @Value: 简单类型的属性赋值
     */
    @Value("${myname}")
    private String name;
    @Value("${myage}")
    private Integer age;
    
    //使用byName
    @Resource(name = "mySchool")
    private School school;

    public Student() {
    }

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        System.out.println("setAge:"+age);
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", school=" + school +
                '}';
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张德帅-001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值