La convención de uso de Maven es mejor que la configuración
Directorio | Usos |
---|---|
$ {basedir} | Almacene pom.xml y todos los subdirectorios |
$ {basedir} / src / main / java | Código fuente Java del proyecto |
$ {basedir} / src / main / resources | Recursos del proyecto, como archivos de propiedades, springmvc.xml |
$ {basedir} / src / test / java | La clase de prueba del proyecto, como el código Junit |
$ {basedir} / src / test / resources | Recursos para probar |
$ {basedir} / src / main / webapp / WEB-INF | Directorio de archivos de aplicaciones web, información de proyectos web, como web.xml, imágenes locales, página de vista jsp |
$ {basedir} / target | Directorio de salida del paquete |
$ {basedir} / target / classes | Compilar directorio de salida |
$ {basedir} / target / test-classes | Probar el directorio de salida de compilación |
Test.java | Maven solo ejecutará automáticamente clases de prueba que cumplan con las reglas de nomenclatura |
~ / .m2 / repositorio | Ubicación del directorio del repositorio local predeterminado de Maven |
1. Crear un proyecto maven
// 创建项目根据目录
~/Desktop$ mkdir MySpringboot
// 按照上面maven的约定创建目录
~/Desktop$ mkdir -p MySpringboot/src/main/java
~/Desktop$ mkdir -p MySpringboot/src/main/resources
~/Desktop$ mkdir -p MySpringboot/src/test/java
~/Desktop$ mkdir -p MySpringboot/src/test/resources
// 在根目录下创建pom.xml文件
~/Desktop$ touch MySpringboot/pom.xml
// 创建好的maven项目目录结构
~/Desktop$ tree MySpringboot
MySpringboot
├── pom.xml
└── src
├── main
│ ├── java
│ └── resources
└── test
├── java
└── resources
7 directories, 1 file
2. Importar dependencias relacionadas con el arranque de primavera
Agregue la siguiente configuración a pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wong</groupId>
<!--与项目名称一致-->
<artifactId>MySpringboot</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
El iniciador de escena spring-boot-starter-web importará las dependencias relacionadas con el desarrollo web en el proyecto. Para más iniciadores de escena, consulte: springboot scene starter
3. Escriba el programa principal: inicie la aplicación Spring Boot
Cree el nombre del paquete com.wong (en realidad el directorio):
~/Desktop/MySpringboot$ mkdir -p src/main/java/com/wong
Cree el programa principal MainApplication.java en el paquete com.wong:
package com.wong;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @SpringBootApplication用于标注主程序
*/
@SpringBootApplication
public class MainApplication{
public static void main(String[] args){
// 启动Spring应用
SpringApplication.run(MainApplication.class,args);
}
}
4. Escribir controlador relacionado con el negocio
Cree un paquete más para almacenar el controlador comercial:
~/Desktop/MySpringboot$ mkdir -p src/main/java/com/wong/controller
Cree el controlador HelloWorldController.java:
package com.wong.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("world")
public class HelloWorldController{
@GetMapping("hi")
public String index(){
return "Hello World!";
}
}
5. Prueba
Ejecute el programa utilizando el comando mvn spring-boot: run:
~/Desktop/MySpringboot$ mvn spring-boot:run
[INFO] Scanning for projects...
...
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)
2020-03-24 22:13:45.941 INFO 20580 --- [ main] com.wong.MainApplication : Starting MainApplication on kyun-HP-348-G3 with PID 20580 (/home/kyun/Desktop/MySpringboot/target/classes started by kyun in /home/kyun/Desktop/MySpringboot)
2020-03-24 22:13:45.944 INFO 20580 --- [ main] com.wong.MainApplication : No active profile set, falling back to default profiles: default
2020-03-24 22:13:46.662 INFO 20580 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-03-24 22:13:46.670 INFO 20580 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-03-24 22:13:46.671 INFO 20580 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.31]
2020-03-24 22:13:46.716 INFO 20580 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-03-24 22:13:46.716 INFO 20580 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 720 ms
2020-03-24 22:13:46.852 INFO 20580 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-03-24 22:13:46.967 INFO 20580 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-03-24 22:13:46.969 INFO 20580 --- [ main] com.wong.MainApplication : Started MainApplication in 1.298 seconds (JVM running for 1.604)
Ingrese http: // localhost: 8080 / world / hi en el navegador:
7. Simplifique la implementación
Puede lanzar el paquete de guerra y publicarlo en el contenedor Tomcat. Puede escribir directamente el paquete jar y luego ejecutarlo directamente con el comando java -jar <name> .jar.
Primero, agregue el siguiente complemento a pom.xml:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Luego ejecute los siguientes comandos de empaquetado:
~/Desktop/MySpringboot$ mvn package spring-boot:repackage
El paquete escrito está en el directorio de destino:
~/Desktop/MySpringboot$ cd target
~/Desktop/MySpringboot/target$ ls
classes maven-status
generated-sources MySpringboot-1.0-SNAPSHOT.jar
generated-test-sources MySpringboot-1.0-SNAPSHOT.jar.original
maven-archiver test-classes
~/Desktop/MySpringboot/target$ java -jar MySpringboot-1.0-SNAPSHOT.jar
...
Eso es todo por crear un proyecto Spring Boot.