【Java Web系列】SpringBoot入门

1、File -->> New -->> Other -->> Gradle Project

2、修改build.gradle文件

plugins {
   	id "org.springframework.boot" version "2.2.4.RELEASE"
	id 'io.spring.dependency-management' version '1.0.9.RELEASE'
	id 'java'
	id 'war'
}

group = 'demo.takchi.chan'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
	maven { url 'https://repo.spring.io/milestone' }
	maven { url 'https://repo.spring.io/snapshot' }
}

// 开启war任务 
war {
    enabled = true
}

// 修改bootWar的文件名称 , 这一步是为了区分可执行war与正常war
bootWar {
    classifier = 'boot'
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}


3、添加Controller以及Servlet初始化文件

Greeting.java

package demo.takchi.chan;

public class Greeting {

	private final long id;
	private final String content;

	public Greeting(long id, String content) {
		this.id = id;
		this.content = content;
	}

	public long getId() {
		return id;
	}

	public String getContent() {
		return content;
	}
}


GreetingController.java

package demo.takchi.chan;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

	private static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();

	@GetMapping("/v1/greeting")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}
}

DemoApplication.java,如果是war包部署到外部容器,需要增加SpringBootServletInitializer子类,并重写其configure方法,或者将main函数所在的类继承SpringBootServletInitializer子类,并重写configure方法。

package demo.takchi.chan;

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

@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(DemoApplication.class);
	}
	
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

4、编译或者通过命令行编译,build后将生成可执行的内嵌容器的war包以及外部容器执行的war包

5、外部容器执行效果

6、内嵌容器执行效果

java -jar build\libs\SpringBootTest-0.0.1-SNAPSHOT-boot.war

发布了65 篇原创文章 · 获赞 30 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/i792439187/article/details/104107857