簡體   English   中英

構建 jar 並運行 spring 從 cmd 啟動

[英]Build jar and run spring boot from cmd

我是 springboot 的新手,使用的是 springboot 2 版本。

我想使用以下命令運行我的 spring 引導應用程序: java -jar my-app-0.0.1-SNAPSHOT.jar從命令提示符。

但是,當我使用 eclipse 構建應用程序時,它會直接調用 myService.getMyMethod() 而不會構建 jar。

我想先構建 jar 文件,然后從命令提示符運行java -jar my-app-0.0.1-SNAPSHOT.jar ,這將調用 myService.getMyMethod()

我已經在 pom.xml 中安裝了 spring-boot-maven-plugin,運行mvn package / mvn install會啟動應用程序但不會在目標文件夾中生成 jar 文件。 mvn clean package 也不起作用,MyApplication 正在使用實現 CommandLineRunner 並開始調用構建方法,因此不會生成構建 jar 文件

我的總機 class:

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

private static String URL = "ws://localhost:8080/spring-mvc-java/chat";

   @Autowired
   private MyService myService;

   public static void main(String[] args) {
       SpringApplication.run(MyApplication.class, args);
   }
   @Override
   public void run(String... args) throws Exception {
       myService.getMyMethod(URL);
   }
}

我的服務class:

@Service
public class MyServiceImpl implements MyService {

     public void getMyMethod(String URL){
           WebSocketClient client = new StandardWebSocketClient();
           WebSocketStompClient stompClient = new WebSocketStompClient(client);
           stompClient.setMessageConverter(new MappingJackson2MessageConverter());
           StompSessionHandler sessionHandler = new MyStompSessionHandler();
           stompClient.connect(URL, sessionHandler);
           new Scanner(System.in).nextLine(); // Don't close immediately.
           }
}
  1. pom.xml添加標簽<packaging>jar</packaging>
  2. 您可以使用命令mvn packagemaven install build maven project 它將在target文件夾中創建.jar文件。
  3. 從存在.jar的位置運行命令 - java -jar jarName.jar

現在您可以訪問您的system

為了運行 jar 和java -jar你應該使用spring-boot-maven-plugin

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
            </plugin>
        </plugins>
    </build>

This plugin will "bake" all the dependencies of the project into the JAR and add some "technical" code that will allow to run this JAR with java -jar (the exact details are kind of out of scope for this question)

如果將其添加到構建中,並運行mvn package / mvn install它將在target文件夾中創建一個大 JAR 旁邊的原始.original original (將重命名為)

您可以使用 WinRAR/WinZIP 打開它,並確保您的所有類都在那里,並且所有依賴項都在BOOT-INF/lib文件夾中。

然后你可以使用java -jar運行項目

按着這些次序

用於 eclipse/spring 工具套件

  • 右鍵單擊項目名稱以獲取這些選項 --> 單擊 run as maven build 右鍵單擊項目名稱以獲取這些選項

  • 將目標添加為 package 並單擊右下角的“運行”按鈕包裝目標

  • jar 文件將在項目的目標文件夾中生成。 您可以找到它,然后運行java -jar命令在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM