springboot启动时使用哪个配置文件_Spring Boot 项目启动时如何读取配置以及初始化资源...

65e82f23f323752f4fcf68502d194c42.png

在开发过程中,我们有时候会遇到非接口调用而出发程序执行任务的一些场景,比如我们使用quartz定时框架通过配置文件来启动定时任务时,或者一些初始化资源场景等触发的任务执行场景。

方法一:注解

通过使用注解@Configuration和@Bean来初始化资源,配置文件当然还是通过@Value进行注入。

1)@Configuration:用于定义配置类,可替换xml配置文件,被注解的类内部一般是包含了一个或者多个@Bean注解的方法。 2)@Bean:产生一个Bean对象,然后将Bean对象交给Spring管理,被注解的方法是会被 AnnotationConfigApplicationContext或者

AnnotationConfgWebApplicationContext扫描,用于构建bean定义,从而初始化Spring容器。产生这个对象的方法Spring只会调用一次,之后Spring就会将这个Bean对象放入自己的Ioc容器中。

补充@Configuration加载Spring:

1)@Configuration配置spring并启动spring容器

2)@Configuration启动容器+@Bean注册Bean

3)@Configuration启动容器+@Component注册Bean

4)使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法

5)配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)

示例

package com.example.andya.demo.conf;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/**
* @author andya
* @create 2020-06-24 14:37
*/@Configurationpublic class InitConfigTest {@Value("${key}")private String key;@Beanpublic String testInit(){
System.out.println("init key: " + key);return key;}}

方法二:CommandLineRunner

实现CommandLineRunner接口,该接口中的Component会在所有Spring的Beans都初始化之后,在SpringApplication的run()之前执行。

多个类需要有顺序的初始化资源时,我们还可以通过类注解@Order(n)进行优先级控制

示例

package com.example.andya.demo.service;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;/**
* @author andya
* @create 2020-06-24 14:47
*/@Componentpublic class CommandLineRunnerTest implements CommandLineRunner {@Value("${key}")private String key;@Overridepublic void run(String... strings) throws Exception {
System.out.println("command line runner, init key: " + key);}}

两个示例的运行结果

54e5ab54e210abd585a1fff61285a27a.png

作者:Hughman

www.jianshu.com/p/3006ed75fceb

往期精选

IntelliJ IDEA 中集成 SonarLint 代码规范与质量检测插件

从零开始,开发一款属于自己的 IDEA 插件,要啥功能就做啥!

MySQL 表之间关联查询时,为什么建议小表驱动大表?

Redisson 是如何实现分布式锁的?

ElasticSearch 的基本概念和集群分布式底层实现

为什么阿里巴巴规定代码中禁用 static 修饰 SimpleDateFormat?

学会 IDEA REST Client 后,Postman就可以丢掉了...

Java 中回调机制,这篇文章解读的明明白白!

Java 程序员面试 10 大“潜规则”,千万不要踩坑!

实战派:一次消息队列 Kafka 卡顿事故排查过程记录!

java.math包中提供的API类 BigDecimal,你真的会用吗?

7bd142c943c9791748092be876245208.png

我就知道你“在看”!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值