#server port
server.port=8081
#add project context path
server.context-path=/demo
再次启动server:
port: 8082
context-path: /demo
1.配置文件添加
server:
port: 8080
cupSize: B
age: 18
content: "cpuSize:${cupSize},age:${age}"
2.java代码
package com.example;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* create leftso.com
*/
@RestController
public class HelloController {
@Value("${cupSize}")//注意写法,获取配置文件中的cupSize
private String cpuSize;
@Value("${age}")
private int age;
@Value("${content}")
private String content;
@RequestMapping(value="/hello",method=RequestMethod.GET)//写法与springMVC有点相似
public String say(){
return "Hello Spring Boot!"+cpuSize+" "+age+" "+content;
}
}
3.访问结果
属性对象方式取值
1.属性文件
server:
port: 8080
cupSize: B
age: 18
content: "cpuSize:${cupSize},age:${age}"
persion:
name: xqlee
age: 18
2.属性文件里面对象对应的bean
package com.example;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "persion") // 这里的person与配置文件一致
public class PersionProperties {
private String name;
private int age;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* the age to set
*/
public void setAge(int age) {
this.age = age;
}
}
3.controller
package com.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* create leftso.com
*/
@RestController
public class HelloController {
@Value("${cupSize}")//注意写法,获取配置文件中的cupSize
private String cpuSize;
@Value("${age}")
private int age;
@Value("${content}")
private String content;
@Autowired
PersionProperties persionProperties;
@RequestMapping(value="/hello",method=RequestMethod.GET)//写法与springMVC有点相似
public String say(){
System.out.println("name:"+persionProperties.getName()+" age:"+persionProperties.getAge());
return "Hello Spring Boot!"+cpuSize+" "+age+" "+content;
}
}
4.执行结果
多配置文件方式
1.复制两份application.yml,分别命名为application-dev.yml application-prod.yml
2.修改prod配置内容
server:
port: 8081
cupSize: B
age: 18
content: "cpuSize:${cupSize},age:${age}"
persion:
name: xqlee2
age: 182
3配置原本的application.yml
spring:
profiles:
active: prod
启动:
由此得出:
已经启用配置文件application-prod.xml
同理,修改application.yml中的active: dev则启动application-dev.yml
spring boot 入门(一)hello word
spring boot入门(二)属性配置
spring boot入门(三)controller的使用
spring boot入门(四)数据库操作
https://www.leftso.com/article/65.html