boot spring 启动 文本_SpringBoot——项目启动时读取配置及初始化资源

介绍

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

方法一:注解

方案

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

@Configuration:用于定义配置类,可替换xml配置文件,被注解的类内部一般是包含了一个或者多个@Bean注解的方法。

@Bean:产生一个Bean对象,然后将Bean对象交给Spring管理,被注解的方法是会被AnnotationConfigApplicationContext或者AnnotationConfgWebApplicationContext扫描,用于构建bean定义,从而初始化Spring容器。产生这个对象的方法Spring只会调用一次,之后Spring就会将这个Bean对象放入自己的Ioc容器中。

补充@Configuration加载Spring:

@Configuration配置spring并启动spring容器

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

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

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

配置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);

}

}

两个示例的运行结果

3006ed75fceb

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值