1.创建bean,把ApplicationArguments类型的参数传递给bean的构造方法:
package cn.edu.tju.domain;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class Person {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Person(ApplicationArguments args){
List<String> argList=args.getOptionValues("username");
this.username=argList.get(0);
}
}
这个实体类的Person构造方法中,args参数就可以用来获取通过命令行传递过来的参数。 2.controller中注入上述bean
package cn.edu.tju.controller;
import cn.edu.tju.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private Person person;
@RequestMapping("getUsername")
public String getUsername(){
return person.getUsername();
}
}
3.打包成jar包,完整pom如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.edu.tju</groupId>
<artifactId>springboot266</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
</parent>
<!-- Additional lines to be added here... -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>cn.edu.tju.Start</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
4.带参数运行jar包:
java -jar D:\springboot266\target\springboot266-1.0-SNAPSHOT.jar --username=newton
5.运行结果,可以看出运行时输入的参数newton被成功注入到了bean中
|