要在 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 容器中可用即可。这是一种非常灵活的方法,可以让你根据需要在不同的地方访问配置属性。