简化Spring开发
入门案例
创建工程


创建Controller类
1 2 3 4 5 6 7 8 9
| @RestController @RequestMapping("/books") public class BookController { @GetMapping("/{id}") public String getById(@PathVariable Integer id){ System.out.println(id); return "hello world SpringBoot"; } }
|
完成
启动app程序,用postman发请求即可看到功能已实现。
起步依赖
切换功能
配置文件格式
读取数据
例如在yml中有如下配置
1 2 3 4 5 6 7 8 9 10 11 12 13
| lesson: SpringBoot
server: port: 80
enterprise: name: 111 age: 11 tel: 123 subject: - aa - 22 - cc
|
读取数据有如下几种方式
用变量加入@Value注解,或者创建environment变量进行自动装配
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @RestController @RequestMapping("/books") public class BookController {
@Value("${lesson}") private String lesson;
@Autowired private Environment environment;
@GetMapping("/{id}") public String getById(@PathVariable Integer id){ System.out.println(id); System.out.println(lesson); System.out.println(environment.getProperty("enterprise.subject[0]")); return "hello world SpringBoot"; } }
|
或者创建实体类并添加注解
1 2
| @Component @ConfigurationProperties(prefix = "enterprise")
|
然后直接自动装配即可使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| @RestController @RequestMapping("/books") public class BookController {
@Value("${lesson}") private String lesson;
@Autowired private Environment environment;
@Autowired private EnterPrise enterPrise;
@GetMapping("/{id}") public String getById(@PathVariable Integer id){ System.out.println(id); System.out.println(lesson); System.out.println(environment.getProperty("enterprise.subject[0]")); System.out.println(enterPrise); return "hello world SpringBoot"; } }
|
环境更改
按如下方式写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| spring: profiles: active: dev
---
spring: config: activate: on-profile: dev
server: port: 9001
---
spring: config: activate: on-profile: pro
server: port: 9002
---
spring: config: activate: on-profile: test
server: port: 9003
|
带参数启动
1
| java -jar springboot.jar --spring.profiles.active=dev
|