现在很多互联网公司或者项目,都使用SpringBoot + SpringCloud,以微服务的形式来提供后台服务。而且既然是微服务,所涉及到的项目就会很多,服务器端口资源就会相当紧张。而且,其实有些项目,如定时任务等,是不需要对外提供服务,也就不需要占用服务器端口的。那么,在SpringBoot项目中,怎么实现呢?其实很简单,如下

1.spirngboot 2.x之前(1):


@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		new SpringApplicationBuilder().sources(Application.class).web(false).run(args);
	}
}

2.spinrboot 2.x之前(2)

@Configuration
@EnableAutoConfiguration
public class MyClass{
    public static void main(String[] args) throws JAXBException {
         SpringApplication app = new SpringApplication(MyClass.class);
         app.setWebEnvironment(false);
         ConfigurableApplicationContext ctx = app.run(args);
    }
}

3.springboot 2.x之后

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(MyApplication.class)
            .web(WebApplicationType.NONE) // .REACTIVE, .SERVLET
            .run(args);
   }
}

那么如何调用自己的业务呢?不用急,看这里,connandLineRunner是随着项目启动一同启动的,可以用来初始化参数,进行一些初始化操作。

@Component
public class CommandLiner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {
    // Put your logic here
  }

}

4.有没有更简单的办法呢?答案是,有的。

spirngboot2.0之前:在peroperties中添加以下代码即可

spring.main.web-environment=false

spirngboot2.0之后:在peroperties中添加以下代码即可

spring.main.web-application-type=none

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐