2.SpringBoot从配置文件中获取属性内容

参考:

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

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值