新建工程:Spring Initializr
SpringBoot就会帮我们建好SpringbootApplication启动类
内容:
package com.fitsoft.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
这里举一个简单的例子来使用:
在resources资源目录下新建application.yml配置文件(比application.properties好用,易维护)
内容:
spring:
profiles:
active: prd
其中prd代表生产环境
application-prd.yml内容:
server:
port: 80
debug: false
logging:
level:
root: info
file: E:/demospringboot.log
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
data-username: root
data-password: root
mall:
config:
name: 优美商城
description: 这是一家化妆品特卖网站
hot-sales: 20
show-advert: true
dev代表测试环境
application-dev.yml内容:
debug: true
logging:
level:
root: info
file: E:/demospringboot.log
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
data-username: root
data-password: root
mall:
config:
name: 爱美商城
description: 这是一家化妆品特卖网站
hot-sales: 20
show-advert: true
这里我们使用的是生产环境举例,端口号为80
新建MyController类
package com.fitsoft.springboot.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author Joker
* @since 2019/9/14 0014 22:36
*/
@Controller
public class MyController {
@Value("${mall.config.name}")
private String name;
@Value("${mall.config.description}")
private String description;
@Value("${mall.config.hot-sales}")
private Integer hotSales;
@Value("${mall.config.show-advert}")
private Boolean showAdvert;
// @RequestMapping("/out")
// @ResponseBody
// public String out(){
// return "success";
// }
@RequestMapping("/info")
@ResponseBody
public String info(){
return String.format("name:%s,description:%s,hot-sales:%s,show-advert:%s",
name, description, hotSales, showAdvert);
}
}
这里使用@Value注解来访问yml文件,并读取配置,运行一下:
效果图:
真香...