首页 > 解决方案 > Spring Boot 应用程序 - 使用没有默认运行的参数调用类

问题描述

我有这两个类:

DemoApplication类

package com.example.springbootstarter.demo;

@SpringBootApplication
public class DemoApplication {

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

}

HelloSpring 类

package com.example.springbootstarter.demo;

@Component
public class HelloSpring {

    String message;

    HelloSpring(@Value("${sbpg.init.welcome-message}") String hellomessage){
        this.message = hellomessage;
    }

    static String param1;
    static String param2;

    public void printHello(){
        System.out.println("Hello Spring!");
        System.out.println("and hey..." + message + " - " + param1 + " - " + param2);

    }

    public static void main(String[] args){
        ApplicationContext context = SpringApplication.run(DemoApplication.class);
        HelloSpring bean = context.getBean(HelloSpring.class);
        param1 = args[0];
        param2 = args[1];
        bean.printHello();
    }
}

应用程序属性

sbpg.init.welcome-message=hellothere

我打算HelloSpring在带有命令行参数的 shell 脚本中使用 Java 命令自行调用,但它似乎不起作用。

有人可能会争辩说,使用 Spring boot 的正确方法是覆盖您编写的每个组件中的 run 方法,但在我的情况下,我只需要根据我的自动化作业(shell 脚本)中的调用调用特定的组件/bean。

我正在使用spring-boot-maven-plugin.

我在 shell 脚本中的 Java 命令没有运气......即使我试图在我的常规命令行中进行测试。

任何指示或帮助?

标签: javaspring-bootmaven

解决方案


我已经检查了你的代码。它运作良好。请检查使用依赖项。我只使用这个:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
    <version>${spring.boot.version}</version>
</dependency>

推荐阅读