参考:
http://blog.didispace.com/Spring-Boot%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/
一、创建配置文件:
创建main\resource\config\beanVal.properties
com.project.name=Spring-boot
com.project.date=2018-10-30
二、创建一个Bean
@Component
@PropertySource(value = { "classpath:config/beanVal.properties" })
public class Project {
@Value("${com.project.name}")
private String name;
@Value("${com.project.date}")
private String date;
省略get、set……
}
或者在properties文件中所需要的参数name的前缀都一样,且bean中属性名也和配置中的名称的最后一段名称一致,就可以使用@ConfigurationProperties指定前缀的方式,如下:
@Component
@PropertySource(value = { "classpath:config/beanVal.properties" })
@ConfigurationProperties(prefix="com.project")
public class Project {
private String name;
private String date;
省略get、set……
}
注意:
1.Spring Boot会默认加载名称为“application.properties”的配置文件,如果本来就是用的是这个配置文件的话,那么bean上的@PropertySource注解就可以省略;
2.如果properties中没有对应的属性,那么使用@Value时会报错,使用@ConfigurationProperties会显示该属性为null;
3.在Spring Boot中多环境配置文件名需要满足application-{profile}.properties
的格式,其中{profile}
对应你的环境标识,比如:
application-dev.properties
:开发环境application-test.properties
:测试环境application-prod.properties
:生产环境
至于哪个具体的配置文件会被加载,需要在application.properties
文件中通过spring.profiles.active
属性来设置,其值对应{profile}
值。
如:spring.profiles.active=test
就会加载application-test.properties
配置文件内容
三、使用Project这个bean的时候,一定使用@Autowired注入。
--------------------------------------------------------------------------
测试可以写一个controller测试,也可以用单元测试,单元测试如下:
package com.demo.spring.boot.bean;
import static org.junit.Assert.assertEquals;//必须是static
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.SpringJUnit4ClassRunner;
//必须是static
import com.demo.spring.boot.App;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=App.class)
public class ProjectTest {
@Autowired
private Project project;
@Test
public void test() {
assertEquals(project.getName(), "Spring-boot");
assertEquals(project.getDate(), "2018-10-30");
}
}