使用SpringBoot框架开发非Web项目

使用SpringBoot框架开发非Web项目

springboot开发非web项目。主要是为了使用其带来的各种开开箱即用的starter。和spring的ioc/di等等。

pom

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.3.RELEASE</version>
</parent>

<dependencies>
	<!-- 仅仅需要基本的starter,不需要web -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
</dependencies>

<build>
	<plugins>
		<plugin>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-maven-plugin</artifactId>
			<configuration>
				<executable>true</executable>
				<includeSystemScope>true</includeSystemScope>
			</configuration>
		</plugin>
	</plugins>
</build>

MainClass

可以在Main方法中自己去启动需要的服务,程序等。不依赖Servlet容器和web服务。仍然可以使用SpringBoot的各种功能。

import java.io.IOException;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Main {

	public static void main(String[] args) throws IOException {

		SpringApplication springApplication = new SpringApplication(Main.class);
		
		ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
		
		// 因为没有Servlet容器运行,所以程序不会阻塞
		System.in.read();
	}
}

1 个赞