如何通过代码获取springboot自定义的启动参数

要在 Spring Boot 中通过代码获取自定义的启动参数,你可以使用 Spring 的 Environment 对象。这个对象包含了应用程序的所有配置属性,包括自定义的启动参数。

以下是获取自定义启动参数的示例代码:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class MyApplication {
    @Autowired
    private Environment environment;

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    public void someMethod() {
        // 获取自定义启动参数的值
        String customParamValue = environment.getProperty("custom.param");
        System.out.println("Custom Parameter: " + customParamValue);
    }
}

在上述示例中,我们注入了 Environment 对象,并使用 getProperty 方法来获取自定义启动参数的值。假设在配置文件(如 application.yml)中已经设置了 custom.param 的值,这个代码将获取并打印出该值。

你可以在应用程序的任何地方使用 Environment 对象来获取启动参数的值,只要它在 Spring 容器中可用即可。这是一种非常灵活的方法,可以让你根据需要在不同的地方访问配置属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot启动后初始化代码可以通过实现ApplicationRunner和CommandLineRunner接口来实现。这两个接口都提供了run方法,用于在Spring Boot应用启动完成后执行自定义的初始化代码。 1. 实现ApplicationRunner接口: ApplicationRunner接口的run方法在Spring Boot启动完成后执行,并且可以访问应用的ApplicationContext。可以通过在实现类上添加@Component注解将其识别为Spring组件,或者通过@Configuration注解将其作为配置类加载。 ```java @Component public class CustomApplicationRunner implements ApplicationRunner { @Autowired private ApplicationContext applicationContext; @Override public void run(ApplicationArguments args) throws Exception { // 执行初始化代码 // 可以通过applicationContext.getBean()获取其他Spring Bean,进行各种初始化操作 } } ``` 2. 实现CommandLineRunner接口: CommandLineRunner接口的run方法也在Spring Boot启动完成后执行,但是它接收的参数是程序启动时的命令行参数。同样可以通过在实现类上添加@Component注解或@Configuration注解来加载。 ```java @Component public class CustomCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { // 执行初始化代码 // 可以通过args参数获取命令行参数,进行各种初始化操作 } } ``` 以上是Spring Boot启动后初始化的代码实现方式,可以根据具体需求选择ApplicationRunner接口或CommandLineRunner接口来编写初始化代码,并在应用启动后执行。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值