Red de conocimiento informático - Material del sitio web - Cómo usar Springboot para crear proyectos dependientes de Maven

Cómo usar Springboot para crear proyectos dependientes de Maven

Recientemente, la empresa utiliza Springboot para crear proyectos, que de hecho es mucho más rápido que la construcción ssh. Sitio web oficial de aprendizaje de Springboot

1. Primero, descargue maven. Descargar maven es muy conveniente para administrar el entorno de configuración del proyecto.

2. Cree un proyecto maven y escríbalo en el archivo pom.xml:

lt; modelVersiongt; groupIdgt; springbootlt;/groupIdgt;

lt;artifactIdgt;testSpringBootlt;/artifactIdgt;

lt;versiongt;0.0.1-SNAPSHOTlt;/versiongt;

lt;namegt;testSpringBootlt;/namegt;

lt;packaginggt;jarlt;/packaginggt;

lt;! -- Heredar paquete principal --gt;

lt; parentgt;

lt; groupIdgt; ;spring-boot-starter-parentlt;/artifactIdgt;

lt;versiongt;1.1.3.RELEASSelt;/versiongt;

lt;relativePathgt;lt;/relativePathgt;

lt;versiongt; p>

lt;/parentgt;

lt;! -- paquete jar de inicio web de spring-boot;

lt; dependenciesgt;

lt; springframework.boot lt;/groupIdgt;

lt;artifactIdgt;spring-boot-starter-weblt;/artifactIdgt;

lt;/dependencygt;

lt ;! --paquete jar jpa, utilizado para operar la base de datos, similar a hibernate--gt;

lt; depende de gt;/ groupIdgt ;

lt;/artifactIdgt; importar org.springframework.context.annotation.ComponentScan

importar org.springframework.context.annotation.Configuration; 5 .context.annotation.Configuration;

@Configuration

@EnableAutoConfiguration

@ComponentScan

Aplicación de clase pública {

public static void main( String[] args) {

SpringApplication.run(Application.class, args);

}

}

5.at com

Cree una clase en .boot.web de la siguiente manera:

package com.boot.web;

import org.springframework.stereotype.Controller;

import org .springframework.web.bind.annotation.RequestMapping;

importar org.springframework.web.bind.annotation.ResponseBody;

@Controller

clase pública MainController {

// @RequestMapping("")

// public String index(){

// return "examples/index";

// }

@@ RequestMapping("/")

@ResponseBody

String home() {

return "¡Hola mundo!";

}

}

@RequestMapping @ ResponseBody

Ambas anotaciones son SpringMVC si no lo haces Ya sabes, puedes echar un vistazo a SpringMVC

6. Agregue un archivo application.properties en recursos

El contenido del archivo se configura de la siguiente manera:

spring. datasource platform=mysql

spring.datasource.url=jdbc:mysql://localhost/springboot?useUnicode=trueamp;characterEncoding=utf-8amp;zeroDateTimeBehavior=convertToNullamp;transformedBitIsBoolean=trueamp;autoReconnect=trueamp; failOverReadOnly= false

spring.datasource.url=jdbc:mySQL://ocalhost/springboot?driver

# Configuración avanzada...

spring.datasource max-active=50

spring.datasource.max-idle=6

spring.datasource.min-idle=2

spring.session-timeout. = 30

server.tomcat.uri-encoding=UTF-8

spring.thymeleaf.prefix=classpath:templates/

spring.thymeleaf.suffix= html

spring.thymeleaf.mode=HTML5

spring.thymeleaf.encoding=UTF-8

spring.thymeleaf.content-type=text/html.

espri

ng.hoja de tomillo. cache=false

Para la configuración de este archivo, consulte el sitio web oficial de springboot

La configuración completa de los parámetros de este archivo es la siguiente (extraída del sitio web oficial )

# === ================== ===================== ============ ==============

# Propiedades comunes de SPRING BOOT

#

# Este archivo de muestra se proporciona como ejemplo. No lo copie completamente en sus propias aplicaciones. config.location= # Ubicación de los archivos de configuración

#Archivos de configuración

spring.profiles.active=#Lista de comas de perfiles activos

#Configuración de la aplicación (SpringApplication )

spring.main.sources=

spring.main.web-environment= #Detección predeterminada

spring.main.show- banner=true

spring.main....= # Ver todas las propiedades de la clase

#Log

logging.path=/var/logs

logging.file=myapp.log

logging.config= # La ubicación del archivo de configuración (classpath predeterminada: logback.xml para iniciar sesión)

logging.level.*= # Nivel de registro, como "logging.level.org. springframework=DEBUG" (TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)

# IDENTITY (ContextIdApplicationContextInitializer)

spring .application.name=

spring.application.index=

#Configuración del servidor integrado (ServerProperties)

server.port=8080

# JACKSON (JacksonProperties)

spring.jackson.thymeleaf.suffix=.html

spring.thymeleaf.mode=HTML5

spring.thymeleaf .codificación =UTF-8

spring.thymeleaf.content-type=text/html # ;charset=lt;encodinggt; Agregado

spring.thymeleaf.cache =true # Establecer en falso.

charSet=UTF-8

spring.freemarker.contentType=text/html

spring.freemarker.exposeRequestAttributes=falseshell.ssh.keyPath=

shell.ssh .port=

shell.telnet.enabled= # configuración de telnet...

shell.telnet.port=

shell.auth.jaas.domain= # Configuración de autenticación...

shell.auth.key.path=

shell.authwww.meidiyazx.com/sitemap.txtname=

shell.authwww. .meidiyazx.com/sitemap.txtpassword=

shell.auth.spring.roles=spring.freemarker.exposeSessionAttributes=false

spring.freemarker.exposeSpringMacroHelpers=false

spring.freemarker.prefix=

spring.freemarker.requestContextAttribute=

shell.auth.key.path=

shell.authwww.meidiyazx com. /sitemap.txtname=

shell.authwww.meidiyazx.com/sitemap.requestContextAttribute=

spring.freemarker.settings.*=

spring.freemarker. suffix=.ftl

spring.freemarker.templateLoaderPath=classpath:/templates/ # Lista separada por comas

spring.freemarker.viewPath=classpath:/templates/ # Lista separada por comas Lista delimitada

.freemarker.viewNames= # Lista blanca de nombres de vistas que se pueden resolver

# GROOVY TEMPLATES (GroovyTemplateAutoConfiguration)

spring.GROOVYTEMPLATES(GroovyTemplateAutoConfiguration)groovy .template.cache=true

spring.groovy.template.charSet=UTF-8

spring.groovy.template.configuration.*= # Ver TemplateConfiguration de Groovy

spring.groovy.template.contentType=text/html

spring.groovy.template.prefix=classpath:/templates/<

/p>

spring.groovy.template.suffix=..charSet=UTF-8

spring.velocity.contentType=text/html

spring.velocity.dateToolAttribute=

spring.velocity.velocity.numberToolAttribute=

spring.velocity.prefix=

spring.velocity.properties.*=

spring.velocity.requestContextAttribute=

spring.velocity.resourceLoaderPath=classpath:/templates/

spring.velocity.suffix=.vm

spring.velocity.requestContext.name= #Whitelist viewNames= # Lista blanca de nombres de vistas resolubles

# Internacionalización (MessageSourceAutoConfiguration)

spring.messages.basename=messages

spring.messages.cacheSeconds=-1

spring.messages.encoding=UTF-8

# Seguridad (SecurityProperties.viewNames= # Lista blanca de nombres de vistas resolubles

# Internacionalización (MessageSourceAutoConfiguration) SEGURIDAD (SecurityProperties)

security.user.name=user # Nombre de usuario de inicio de sesión

security.user.password= # Contraseña de inicio de sesión

security.user.role=USUARIO # Rol asignado al usuario

security.require-ssl=false # Configuración avanzada...

seguridad .enable-csrf=false

security.basic.enabled=true

spring.batch.schema= # Modo por lotes para cargar

# AOP

spring.aop. auto=

# GIT INFO

spring.git.properties= # Referencia de recursos del archivo de propiedades de información git generado

7. Busque la aplicación en com. inicie, inicie com.boot como una aplicación java, luego abra el navegador e ingrese localhost:8080 y aparecerá Hello World.

Se completa un desarrollo web tan simple.