@SpringBootApplication&多环境配置&引入外部配置信息
1.@SpringBootApplication概述
@SpringBootApplication是一个组合注解
(1)@SpringBootApplication就是@Configuration注解,代表启动类就是配置类

(2)@EnableAutoConfiguration帮你实现自动装配,SpringBoot工程启动时,运行一个SpringFactoriesLoader的类,加载META-INF/spring.factories配置类(已经开启的),通过SpringFactoriesLoader中的load方法,以for循环的方式,一个一个加载。
好处:无需编写大量的整合配置信息,只需要按照SpringBoot提供好了约定去整合即可。
坏处:如果说你导入一个starter依赖,那么你就需要填写他必要的配置信息。
手动关闭自动装配指定内容:@SpringBootApplication(exclude=QuartzAutoConfiguration.class)
就是帮你去实现之前SpringMVC里面的内容,不用再自己写了

(3)@ComponentScan就相当于<context:component-scan basePackage="包名"/>,帮助扫描注解的

2.多环境配置
多环境配置,指的就是,我们在开发时候,如指定一个port,部署的时候指定另外一个port,我们直接可以在appliaction中预加
在application.yml文件中添加一个配置项:
spring:
profiles:
active: 环境名
在resource目录下,创建多个application-环境名.yml文件即可
在部署工程时,通过java -jar jar文件 --spring.profiles.active=环境

开发时候用的application-dev.yml,需要在application.yml中指定
application.yml

在application-dev.yml

在application-prov.yml

当我部署的时候,直接用jar包,不用再手动修改yml文件中内容


也可以在application.yml中将三个yml合并成一个

3.引入外部配置文件信息
和传统的SSM方式一样,通过@Value的注解去获取properties/yml文件中的内容

在controller中


如果在yml中需要编写大量的自定义配置,并且具有统一的前缀时,可以采用如下的方式


package com.company.demo.properites;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "aliyun")
@Component
@Data
public class AliyunProperties {
private String xxxx;
private String yyyy;
private String aaaa;
private String bbbb;
}
HelloController.java
package com.company.demo.controller;
import com.company.demo.entiy.User;
import com.company.demo.properites.AliyunProperties;
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;
import javax.annotation.Resource;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello Spring Boot!!!!******";
}
@Resource(name = "user1")
private User user;
@GetMapping("/user")
public User user() {
return user;
}
@Value("${picPath}")
private String picPath;
@GetMapping("/picPath")
public String picPath() {
return picPath;
}
@Autowired
private AliyunProperties aliyunProperties;
@GetMapping("/aliyun")
public AliyunProperties aliyun() {
return aliyunProperties;
}
}


浙公网安备 33010602011771号