您的位置:首页 > 移动开发

SpringBoot配置文件application.yml (application.properties)

2017-11-13 12:30 1306 查看
尽管SpringBoot提倡零配置,但我们在实际项目使用时,为了方便,依然少不了一些外部配置。我们很庆幸的是,SpringBoot支持使用外部配置文件,同时SpringBoot也有默认的配置文件application.properties(我更喜欢将他命名为application.yml,二者写法不同,作用相同)。

一、SpringBoot 默认配置文件 application.yml

接上一篇的HelloWorld,我们发现SpringBoot指定的默认端口为8080,但实际上,很多时候我们需要自定义服务端口,只需在application.yml中添加server:port: XXXX ,便可轻而易举地改变服务端口。

server:
port: 8680


如上,我将服务的端口定为8680,再次启动我们的HelloWorld,访问 http://localhost:8680/hello

二、在application.yml文件中自定义属性

在实际项目中,我们可能需要一些自定义的属性来使我们的项目配置更方便,下面的例子来演示我们如何在默认的配置文件中添加我们自定义的属性并运用它。

server:
port: 8680

test:
msg: welcome to study springBoot


如上,我们添加一个test.msg的自定义属性,下面我们在HelloWorldController中分别用两种不同的方式使用它。

1、@Value

//读取配置文件中的test.msg
@Value("${test.msg}")
private String testMesg;

//定义一个测试接口index
@GetMapping("/index")
public String index(){
return "读取核心配置文件application的内容方式一,使用@Value方式:" + testMesg;
}


访问 http://localhost:8680/index

结果:页面上显示出了配置文件中的内容 …… “welcome to study springBoot”

2、使用 Environment

@Autowired
private Environment env;
@GetMapping("/index2")
public String index2(){
4000
return "读取核心配置文件application的内容方式二,使用Environment方式:" + env.getProperty("test.msg");
}


访问 http://localhost:8680/index2

三、使用自定义的配置文件

有时候,我们可能 并不想将将一些配置写进默认的application.properties中,而是自定义一个配置文件来设置我们的专属配置。下面,我们在resources文件夹下创建一个hello.properties文件。

prop.name: libin
prop.age: 18


然后写一个自定义配置的实体类HelloProperties,为了构鲜明,我们新建一个properties包,将HelloProperties放在这个包下。

package cn.pw.pf.web.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
* 自定义配置的实体类
* @Description:
* @Author:libin
* @Date: Created in 10:57 2017/11/13
*/
@Component
@PropertySource(value= "classpath:hello.properties")
@ConfigurationProperties(prefix = "prop")
public class HelloProperties {
private String name;
private int age;

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}


最后,我们在仍然在HelloWorldController中测试。

@Autowired
private HelloProperties hello;

@GetMapping("/index3")
public String index3(){
return "读取自定义配置文件内容:" + hello.getName() + "今年" + hello.getAge() + "岁!";
}


访问 http://localhost:8680/index3

页面上显示出了我们在配置文件中定义的属性值。

重点强调:下面两个配置

@PropertySource(value= “classpath:hello.properties”)

@ConfigurationProperties(prefix = “prop”)

在1.5版本以前,@ConfigurationProperties 中有locations属性,可以指定文件位置。

1.5版本以后,@ConfigurationProperties去掉了 locations 属性,所以在这里使用了@PropertySource来代替。但是,@PropertySource注解只可以加载proprties文件,无法加载yaml文件,像笔者一样对yaml文件有情结的同学,估计得暂时委曲求全,使用默认的application.yml配置了。

SpringBoot配置文件的基本使用就写这么多了,下一篇我们结合thymeleaf写一个简单的登陆。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐