嘿,我是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); } }
当我尝试运行此程序时,出现异常。
有没有一种方法可以同时调用两个run方法?
-堆栈跟踪
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)
我认为您尝试使用两种配置运行一个spring应用程序。
通常的方法是使用@Import注释。
@Import
@ComponentScan @EnableAutoConfiguration @Import(ScheduledTasks.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@See Spring参考第4.12.5章使用@Import批注组合基于Java的配置