application-(生产环境).yaml
的方式即可java -jar xxx.jar --spring.profiles.active=环境名
spring.profiles.active=环境
package com.atguigu.boot05.bean;
/**
* @author Bonbons
* @version 1.0
*/
public interface Person {
String getName();
Integer getAge();
}
package com.atguigu.boot05.bean;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
* @author Bonbons
* @version 1.0
*/
@Data
@Profile("prod")
@Component
@ConfigurationProperties("person")
public class Boss implements Person{
private String name;
private Integer age;
}
package com.atguigu.boot05.bean;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/**
* @author Bonbons
* @version 1.0
*/
@Data
@Profile("test")
@Component
@ConfigurationProperties("person")
public class Employee implements Person{
private String name;
private Integer age;
}
@Autowired
Person person;
@GetMapping("/")
public String hello(){
return person.getClass().toString();
}
application.properties
person.name=boss
server.port=8080
spring.profiles.active=prod
application-prod.yaml
person:
name: prod-boss
server:
port: 8000
application-test.yaml
person:
name: test-boss
age: 25
server:
port: 7000
application.properties
person.name=boss
server.port=8080
spring.profiles.active=myprod
spring.profiles.group.myprod[0]=ppd
spring.profiles.group.myprod[1]=prod
spring.profiles.group.mytest[0]=test
application-ppd.yaml
person:
age: 21
我们将所有的信息抽取成一个文件放在web里面集中管理——外部化配置
详情可以参考官方文档
外部化配置截图:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4XAodyyu-1680057177430)(attachment:cfd409b05609c96f001bbe38142151d3)]
Java属性文件
yaml文件
环境变量【电脑本机里面配置的】
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o9DB5X7o-1680057177432)(attachment:39fcd3a0363be69a1f480542906580bf)]
命令行参数
(1)classpath 根路径下
(2)classpath 根路径下的 config 目录
(3)jar 包当前目录
(4)jar 包当前目录下的 config目录
(5) /config子目录的直接子目录
这个需要在Linux服务器的根目录下进行操作
autoconfigure包中配置使用 META-INF/spring.factories 中 EnableAutoConfiguration 的值,使得项目启动加载指定的自动配置类
编写自动配置类 xxxAutoConfiguration -> xxxxProperties
引入starter — xxxAutoConfiguration — 容器中放入组件 ---- 绑定xxxProperties ---- 配置项
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
} // ↑ 创建SpringApplication ↑ 运行SpringApplication
保存一些信息
判定当前应用的类型 -> ClassUtils: Servlet
// WebApplicationType类 >> 判断类型
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
return WebApplicationType.REACTIVE; // 返回响应式编程类型
}
for (String className : SERVLET_INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET; // 返回SERVLET编程类型
}
bootstrappers: 初始启动引导器(List
: 去spring.factories 文件中找 org.springframework.boot.Bootstrapper
找 ApplicationContextInitializer(初始化器);去spring.factories找 ApplicationContextInitializer
List<ApplicationContextInitializer<?>> initializers
List<ApplicationListener<?>> listeners
// 构造方法
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// WebApplicationType是枚举类 有NONE,SERVLET,REACTIVE 下行webApplicationType是SERVLET
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 初始启动引导器 去spring.factories文件中找org.springframework.boot.Bootstrapper 但我找不到实现Bootstrapper接口的类
this.bootstrappers = new ArrayList<>(getSpringFactoriesInstances(Bootstrapper.class));
// 去spring.factories找 ApplicationContextInitializer
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 去spring.factories找 ApplicationListener
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass(); // 决定哪个类是我们的主程序
} // ↓
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
// 哪个类有main方法 被找到的第1个类就是主程序类
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
总结:应用创建的过程就是把一些关键的组件信息读取并保存到 SpringAppication中,作为运行SpringApplication的前置工作
```java
public interface Bootstrapper {
/**
* Initialize the given {@link BootstrapRegistry} with any required registrations.
* @param registry the registry to initialize
*/
void intitialize(BootstrapRegistry registry);
}
```
// Instantiate all remaining (non-lazy-init) singletons. 使用单例模式 实例化所有剩余的(非延迟初始化)组件。
finishBeanFactoryInitialization(beanFactory);
@FunctionalInterface
public interface ApplicationRunner {
/**
* Callback used to run the bean.
* @param args incoming application arguments
* @throws Exception on error
*/
void run(ApplicationArguments args) throws Exception;
}
@FunctionalInterface
public interface CommandLineRunner {
/**
* Callback used to run the bean.
* @param args incoming main method arguments
* @throws Exception on error
*/
void run(String... args) throws Exception;
}
// run()方法
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();//开始计时器
stopWatch.start();//开始计时
// 1.
// 创建引导上下文(Context环境)createBootstrapContext()
// 获取到所有之前的 bootstrappers 挨个执行 intitialize() 来完成对引导启动器上下文环境设置
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
// 2.到最后该方法会返回这context
ConfigurableApplicationContext context = null;
// 3.让当前应用进入headless模式
configureHeadlessProperty();
// 4.获取所有 RunListener(运行监听器)为了方便所有Listener进行事件感知
SpringApplicationRunListeners listeners = getRunListeners(args);
// 5. 遍历 SpringApplicationRunListener 调用starting方法
// 相当于通知所有感兴趣系统正在启动过程的人 项目正在starting
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
// 6.保存命令行参数 ApplicationArguments
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 7.准备环境
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
configureIgnoreBeanInfo(environment);
/*
打印标志
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.2)
*/
Banner printedBanner = printBanner(environment);
// 创建IOC容器(createApplicationContext())
// 根据项目类型webApplicationType(NONE,SERVLET,REACTIVE)创建容器,
// 当前会创建 AnnotationConfigServletWebServerApplicationContext
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
// 8.准备ApplicationContext IOC容器的基本信息
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
// 9.刷新IOC容器 创建容器中的所有组件 Spring框架的内容
refreshContext(context);
// 该方法没内容,大概为将来填入
afterRefresh(context, applicationArguments);
stopWatch.stop(); // 停止计时
if (this.logStartupInfo) { // this.logStartupInfo默认是true
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
// 10.
listeners.started(context);
// 11.调用所有runners
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
// 13.
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
// 12.
listeners.running(context);
}
catch (Throwable ex) {
// 13.
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
return context;
}
Ctrl + O 快速批量实现接口方法
MyApplicationContextInitializer
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("MyApplicationContextInitializer ....initialize.... ");
}
}
MyApplicationListener
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class MyApplicationListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.println("MyApplicationListener.....onApplicationEvent...");
}
}
MySpringApplicationRunListener
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class MySpringApplicationRunListener implements SpringApplicationRunListener {
private SpringApplication application;
public MySpringApplicationRunListener(SpringApplication application, String[] args){
this.application = application;
}
@Override
public void starting(ConfigurableBootstrapContext bootstrapContext) {
System.out.println("MySpringApplicationRunListener....starting....");
}
@Override
public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
System.out.println("MySpringApplicationRunListener....environmentPrepared....");
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
System.out.println("MySpringApplicationRunListener....contextPrepared....");
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
System.out.println("MySpringApplicationRunListener....contextLoaded....");
}
@Override
public void started(ConfigurableApplicationContext context) {
System.out.println("MySpringApplicationRunListener....started....");
}
@Override
public void running(ConfigurableApplicationContext context) {
System.out.println("MySpringApplicationRunListener....running....");
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
System.out.println("MySpringApplicationRunListener....failed....");
}
}
MyApplicationRunner
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(1) // 按照Order排序 数字越大优先级越高
@Component // 放入容器
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("MyApplicationRunner...run...");
}
}
MyCommandLineRunner
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 应用启动做一个一次性事情
*/
@Order(2) // 按照Order排序
@Component // 放入容器
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("MyCommandLineRunner....run....");
}
}
注册MyApplicationContextInitializer,MyApplicationListener,MySpringApplicationRunListener
org.springframework.context.ApplicationContextInitializer=\
com.atguigu.boot.listener.MyApplicationContextInitializer
org.springframework.context.ApplicationListener=\
com.atguigu.boot.listener.MyApplicationListener
org.springframework.boot.SpringApplicationRunListener=\
com.atguigu.boot.listener.MySpringApplicationRunListener