SpringBoot学习笔记八、读取配置文件

  • application.properties添加测试配置项

test.a=aaa
test.b=bbb
test.c=ccc

  • 方式一、属性注入,相关注解:@Value

    @Value("${test.a}")
    String a;
    
    @Test
    public void 测试属性注入(){
        Assert.assertEquals("aaa",a);
    }

  • 方式二、实体类映射,

相关注解:@Component、@ConfigurationProperties、@PropertySource,

备注1:prefix加上实体类属性名要对应配置文件的属性名,也可以同时使用@Value注入其他属性

备注2:@PropertySource(value="classpath:application.properties") 此注解不配置时默认application.properties,可省略

package com.example.demo.domain;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix="test")
@PropertySource(value="classpath:application.properties")
public class TestSettings {
    
    private String a;
    
    private String b;
    
    private String c;
    
    @Value("${test.c}")
    private String d;

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public String getB() {
        return b;
    }

    public void setB(String b) {
        this.b = b;
    }

    public String getC() {
        return c;
    }

    public void setC(String c) {
        this.c = c;
    }

    public String getD() {
        return d;
    }

    public void setD(String d) {
        this.d = d;
    }

    @Override
    public String toString() {
        return "TestSettings [a=" + a + ", b=" + b + ", c=" + c + ", d=" + d + "]";
    }

}
 

  • 测试类

package com.example.demo;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.demo.domain.TestSettings;

@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
    
    @Value("${test.a}")
    private String a;
    
    @Test
    public void 测试属性注入(){
        Assert.assertEquals("aaa",a);
    }
    
    @Autowired
    private TestSettings testSettings;
    
    @Test
    public void 测试对象注入(){
        System.out.println(testSettings.toString());
        Assert.assertEquals("aaa",testSettings.getA());
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值