spring-boot 如何加载rsources下面的自定义配置文件

来源:互联网 发布:mysql设置主键 guid 编辑:程序博客网 时间:2024/06/05 14:41

1.创建一个自定义properties文件,如下:

config.msg = hello world!
config.name = "潘浩"


2.写一个读取配置文件的类

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


@Component
@PropertySource("classpath:config.properties")
/**
 * 在@ConfigurationProperties注释中有两个属性:
prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以web.开头)
 * @author 潘浩
 */
public class MyConfig {


@Value("${config.msg}")
private String msg;

@Value("${config.name}")
private String name;


public String getMsg() {
return msg;
}


public String getName() {
return name;
}

}

3.写一个测试类可以测试是否成功读取配置文件中的属性.


/**
 * 测试类
 * 
 * @author 潘浩
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=GlsserviceProviderProjectMgrApplication.class)  // 指定spring-boot的启动类   
public class ControllerTest {

@Autowired
    private MyConfig myConfig;

@Test
public void test_如何获取配置文件中的属性值()
{
System.out.println("test_如何获取配置文件中的属性值: "+myConfig.getMsg());
}
}



原创粉丝点击