springboot默认启动入口函数是支持接收参数,并且在整个应用程序内部也可以获取到这些参数,并且如果传递的参数是一些内部定义的参数将会被映射到springboot内部配置项,从而达到配置效果。
springboot入口参数传递与获取:
方式1)springboot 配置项目启动传递参数:
a)在idea导航Run->Edit Configuration...

b)Edit Configuration...下设置启动参数:

c)修改SpringBoot启动入口函数:

package app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import java.util.Arrays;
@ComponentScan("com.dx.controller")
@EnableAutoConfiguration
public class App {
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
SpringApplication.run(App.class, args);
}
}

d)在HelloWordController.java类中通过ApplicationArguments获取入口参数:

package com.dx.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class HelloWordController {
@Autowired
private ApplicationArguments applicationArguments;
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
System.out.println(applicationArguments.getNonOptionArgs());
System.out.println("index is running...");
return "welcome";
}
}

e)启动时,参看打印信息:

f)在浏览器中访问http://localhost:8888/index,查看打印输出信息:

方式2)springboot jar包运行时传递参数:
a)通过maven打包项目为jar包;
b)cmd中运行java -jar xxx.jar username=root password=pwd;
c)查看启动信息;
d)浏览器访问http://localhsot:8888/index,查看cmd屏幕输出信息。
springboot传递系统内部定义配置参数:
1)修改上述参数"username=root password=pwd"为"spring.config.name=application888 username=root password=pwd"
2)此时在src下、src\resources、src\resources\config其中任意目录下添加application888.properties 文件,并修改内容为:
server.port=8880
,此时启动项目,将会发现启动端口已经发生变更,变更为8880端口。
感谢您的阅读,如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮。本文欢迎各位转载,但是转载文章之后必须在文章页面中给出作者和原文连接。
基础才是编程人员应该深入研究的问题,比如:
1)List/Set/Map内部组成原理|区别
2)mysql索引存储结构&如何调优/b-tree特点、计算复杂度及影响复杂度的因素。。。
3)JVM运行组成与原理及调优
4)Java类加载器运行原理
5)Java中GC过程原理|使用的回收算法原理
6)Redis中hash一致性实现及与hash其他区别
7)Java多线程、线程池开发、管理Lock与Synchroined区别
8)Spring IOC/AOP 原理;加载过程的。。。
【+加关注】。
本文详细介绍了SpringBoot中参数的传递方式,包括在IDEA中设置启动参数、通过ApplicationArguments获取参数,以及在运行jar包时传递参数。同时,还讲解了如何通过传递系统内部定义的配置参数来修改SpringBoot的默认行为。
1万+

被折叠的 条评论
为什么被折叠?



