Spring Boot 项目启动时如何读取配置以及初始化资源
方法一:注解
通过使用注解@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 */ @Configuration public class InitConfigTest { @Value("${key}") private String key; @Bean public 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 */ @Component public class CommandLineRunnerTest implements CommandLineRunner { @Value("${key}") private String key; @Override public void run(String... strings) throws Exception { System.out.println("command line runner, init key: " + key); } }
两个示例的运行结果
故乡明
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话