跟着DD后面学习Spring Boot(三)

三.Spring Boot属性配置详解:

看了一些文章,感觉Spring Boot就像是为了减轻Spring的工作量而创作出来的,前面也提到过,我不熟悉任何框架,对Spring也不了解,在这里写下这些,只是为了记录我学习Spring Boot的一个历程。是跟着DD后面学习的一个历程。



关于application.properties的使用,主要用来配置数据库连接、日志相关配置等。除了这些配置内容之外,本文将具体介绍一些在application.properties配置中的其他特性和使用方法。

自定义属性与加载:

还是得有个主程序入口:



在 application.properties 中添加自己需要的定义的属性:

blog.name = DD
blog.title = Spring Boot

通过@Value("${属性名}")注解来加载对应的配置属性:

package com.example.demo;

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

@Component
public class BlogProperties {
    @Value("${blog.name}")
    private String name;

    @Value("${blog.title}")
    private String title;

    public String getName() {
        return name;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

在测试单元下新建ApplicationTests类,测试:

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.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest

public class ApplicationTests {

    @Autowired
    private BlogProperties blogProperties;

    @Test
    public void getHello() throws Exception{
        Assert.assertEquals(blogProperties.getName(),"DD");
        Assert.assertEquals(blogProperties.getTitle(),"Spring Boot");
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值