springboot 2.4 随手笔记

2.1 Using the “default” Package
最好避免用default 包

2.2 main函数主类加@SpringBootApplication,如果不用的话,可以用@EnableAutoConfiguration和@ComponentScan代替

2.3 配置类 @Configuration
最好用配置类,不要用xml

3.1 增加配置类
不需要把配置类都写在一个类中,可以用@Import导入其他配置类,
或者用ComponentScan 自动装配spring组件,包括@Configuration配置类

3.2 导入XML配置
@ImportResource 可以导入xml配置文件

4.2 禁用自动装配
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
或者在属性文件中配置spring.autoconfigure.exclude

5 Spring Beans and Dependency Injection
@ComponentScan (查找bean)和@Autowired(构造器注入)使用效果很好,如果项目结构和推荐的一样,主类放在根目录下,那么@ComponentScan 不用添加参数。
各种应用组件(@Component, @Service, @Repository, @Controller等等)都会自动注册为spring beans

7.3 maven插件
$ mvn spring-boot:run 运行

8.2.4 禁用重启
devtools不想重启可以设置spring.devtools.restart.enabled 属性
或者在run之前设置
System.setProperty(“spring.devtools.restart.enabled”, “false”);

Spring Boot Features
1 SpringApplication
默认启动的时候,日志是info级别,启动日志可以通过设置spring.main.log-startup-info为false来关闭

1.1 Startup Failure
启动错误的时候,已注册的FailureAnalyzers 打印错误信息

1.2 懒加载
bean只有被使用的时候才创建,spring.main.lazy-initialization=true

1.3 自定义banner
将banner.txt加到类路径,或者设置spring.banner.location属性。
也可以设置jpg,gif等类型,并且设置spring.banner.image.location属性。

1.4 自定义 SpringApplication
比如关闭banner

public static void main(String[] args) {
   
    SpringApplication app = new SpringApplication(MySpringConfiguration.class);
    app.setBannerMode(Banner.Mode.OFF);
    app.run(args);
}

1.5 链式编程启动

new SpringApplicationBuilder()
       .sources(Parent.class)
       .child(Application.class)
       .bannerMode(Banner.Mode.OFF)
       .run(args);

1.6.3 管理应用程序可用性状态
例如,我们可以将应用程序的“就绪”状态导出到一个文件中,以便Kubernetes的“ exec Probe”可以查看此文件:

@Component
public class ReadinessStateExporter {
   

    @EventListener
    public void onStateChange(AvailabilityChangeEvent<ReadinessState> event) {
   
        switch (event.getState()) {
   
        case ACCEPTING_TRAFFIC:
            // create file /tmp/healthy
        break;
        case REFUSING_TRAFFIC:
            // remove file /tmp/healthy
        break;
        }
    }
}

当应用程序崩溃且无法恢复时,我们还可以更新应用程序的状态:

@Component
public class LocalCacheVerifier {
   

    private final ApplicationEventPublisher eventPublisher;

    public LocalCacheVerifier(ApplicationEventPublisher eventPublisher) {
   
        this.eventPublisher = eventPublisher;
    }

    public void checkLocalCache() {
   
        try {
   
            //...
        }
        catch (CacheCompletelyBrokenException ex) {
   
            AvailabilityChangeEvent.publish
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值