1.多配置文件
在工作中,有dev,test,pre等各种环境。每个环境的配置又不一样。以下有两种方式可以配置使用。
1.1.第一种方式
同一个配置文件(application.yml)中划分不同的环境配置。
server:
port: 8080
spring:
# 环境激活使用。
profiles:
active: prod
---
server:
port: 9001
# 多属性配置文件时,按照启动时的环境进行激活配置。如这个配置会在default环境下生效
spring:
config:
activate:
on-profile: default
---
server:
port: 9002
spring:
config:
activate:
on-profile: prod
注意
- 同一个文件中的不同环境配置,需要确定文件在什么时候激活。如上图中的注释。
- 默认使用的配置文件是default。所以要使用具体环境的配置文件有效,就需要激活对应的文件。如上图中 --> active:prod(环境)。
1.2第二种方式
独立配置文件。就是在和application.yml[properties|yaml]相同的目录下,建立对应环境的配置文件。
注意
文件的命名方式为 application-{profile}.yml
2.如何修改Banner的位置
SpringBoot控制台打印的Banner默认位置是在“classpath:banner.txt”下。想要修改位置,请参照下图。
spring:
# springboot启动时的banner图。默认的banner图在resources/banner.txt
banner:
# 自定义banner图的位置。
location: classpath:static/banner.txt
注意
如果修改控制台默认banner图并且没有使用上图的配置,那么banner文件的名称就需要是banner.txt。
2.1.如何查看springboot默认的banner。
2.2.如何自定义banner的打印。
参考SpringBootBanner的方式,直接实现Banner接口,自定义打印内容。
3.如何控制具体的Bean在具体的环境中生效
@Profile注解控制某Bean可以在切换到dev环境中生效。当yml中的属性spring.profiles.active:dev 被激活之后,相应的bean也就被激活。
4.如何制作SpringBoot启动器
4.1.第一步,引入所需依赖
<dependencies>
<!--启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--自动配置依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
4.2.第二步,制作自动配置类和配置属性
import com.lin.timer.starter.properties.TimerProperties;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
/**
* @author linjiang
* @date 2024/7/24
* @fn
*/
@Configuration
@EnableConfigurationProperties(TimerProperties.class)
@ConditionalOnClass(TimerProperties.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 100)
@Import({TimerConfiguration.class})
public class TimerAutoConfiguration {
}
@ConfigurationProperties(prefix = "timer")
public class TimerProperties {
private Integer num;
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
@Override
public String toString() {
return "TimerProperties{" +
"num=" + num +
'}';
}
}
4.3.第三步,敲定业务逻辑和业务配置类。
@ConditionalOnClass(TimerService.class)
public class TimerConfiguration {
@Resource
TimerProperties properties;
@Bean
@ConditionalOnMissingBean
public TimerService timerService() {
return new TimerService(properties);
}
}
public class TimerService {
TimerProperties properties;
public TimerService(TimerProperties properties) {
this.properties = properties;
}
public void timer() {
System.out.println("获取到的属性:" + properties);
}
}