springboot启动的时候注入代码

springboot启动的时候注入代码

在Spring Boot中,你可以通过实现CommandLineRunnerApplicationRunner接口在应用启动时注入自定义代码。以下是两种方式的简单示例:

使用CommandLineRunner接口

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
 
@SpringBootApplication
public class MyApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
 
    @Bean
    public CommandLineRunner run() {
        return args -> {
            // 在这里编写启动时需要执行的代码
            System.out.println("Spring Boot 应用已启动,可以在这里运行自定义代码。");
        };
    }
}

使用ApplicationRunner接口

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
 
@SpringBootApplication
public class MyApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
 
    @Bean
    public ApplicationRunner appRunner() {
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) throws Exception {
                // 在这里编写启动时需要执行的代码
                System.out.println("Spring Boot 应用已启动,可以在这里运行自定义代码。");
            }
        };
    }
}

在以上两种方式中,你可以在run()方法或appRunner()方法中编写你需要在应用启动时执行的代码。这些代码会在Spring Boot完成启动流程之后,应用上下文完全初始化之前执行。

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值