跟着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");
}
}