Spring:运行多个" SpringApplication.Run()"在应用主要方法

时间:2014-07-01 17:24:40

标签: java spring main spring-boot

嘿,我是Spring的新手,我正在尝试在我的Applications.java中运行多个run方法。

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
@EnableAutoConfiguration
public class Application {

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

当我尝试运行时,我得到一个例外。

有没有办法在main中调用两个run方法?

-StackTrace

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:135)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:120)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:683)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:313)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:944)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:933)
    at testWebApp.Application.main(Application.java:13)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)

3 个答案:

答案 0 :(得分:7)

我认为您尝试使用两种配置运行一个spring应用程序。

执行此操作的常规方法是使用@Import注释。

@ComponentScan
@EnableAutoConfiguration
@Import(ScheduledTasks.class)
public class Application {

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

@See Spring Reference Chapter 4.12.5 Composing Java-based configurations Using the @Import annotation

答案 1 :(得分:5)

run方法支持一个Objects数组。此代码有效

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        Object[] sources = {Application.class, ScheduledTasks.class};
        SpringApplication.run(sources, args);
    }
}

答案 2 :(得分:1)

没有看到代码就无法说出来,但我的猜测是你试图用同一个端口启动2个webapps。您可以更改其中一个端口,或将其设置为非Web应用程序。我建议使用SpringApplicationBuilder来设置这些内容。