-
关于创建springboot项目之前已经说过了,本文将通过hello的项目原型讲解。
创建springboot项目 -
在resources的文件目录下创建application.yml,一般配置文件一个就可以了,将application.properties删除。
application.yml的代码,一定注意值和属性之间有:和空格。
helloWorld: "Hello World"
HelloController.java的代码。
package com.luffykaiyuan.hello.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Value("${helloWorld}")
private String hello;
@GetMapping("/hello")
public String say(){
return hello;
}
}
使用@Value获取配置文件中的值。
- 获取多个值的配置
当需要获取的值多了,不可以一大串@Value注解,显得冗余。
我们可以将配置的属性看成一个对象的属性。
yml文件配置
limit:
hello: "newHello"
world: "newWorld"
新建一个对象HelloWorld.java。
package com.luffykaiyuan.hello;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "limit")
public class HelloWorld {
private String hello;
private String world;
public void setHello(String hello) {
this.hello = hello;
}
public void setWorld(String world) {
this.world = world;
}
public String getHello() {
return hello;
}
public String getWorld() {
return world;
}
}
通过ConfigurationProperties注解获取文件,prefix 获取前缀,当有多个前缀时用.分割。
注意属性名必须和yml中的对应。
最后controller中
package com.luffykaiyuan.hello.controller;
import com.luffykaiyuan.hello.HelloWorld;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@Autowired
private HelloWorld hello;
@GetMapping("/hello")
public String say(){
return hello.getHello() + "-----" + hello.getWorld();
}
}
启动运行结果。