Tabla de contenido
Primero, el método común para leer archivos de configuración en SpringBoot
1.1, usa @Value para leer
En el ciclo de declaración de SpringBoot, puede usar la anotación @Value para leer la información de configuración del archivo de configuración predeterminado de SpringBoot.
例如在Controller中使用:
// 在配置文件中读取属性名为web.images-path对应的值
@Value("${web.images-path}")
private String path;
@Value se puede colocar en propiedades o métodos. El requisito previo para el uso normal es que la clase debe estar dentro del ciclo de vida de SpringBoot.
¿Cómo ponemos una clase en el ciclo de vida de Spring para su gestión? La anotación @Component se utiliza
porque @Controller y @Service contienen @Component. Por lo que se puede utilizar directamente.
下面是单独使用@Component的例子
Cree un paquete de configuración, luego cree BootProperties
package com.demo.config;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
@Component
public class BootProperties {
@Value("${web.images-path}")
public String path;
}
Luego escribe en el controlador.
@RestController
public class HelloController {
@Autowired
private BootProperties bootProperties;
@RequestMapping("/test5")
public Object test5(){
return bootProperties.path;
}
}
使用ing类型写
package com.demo.config;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
@Component
public class BootProperties {
@Value("${web.images-path}")
public String path;
@Value("${server.port}")
public int port;
}
@RestController
public class HelloController {
@Autowired
private BootProperties bootProperties;
@RequestMapping("/test5")
public Object test5(){
return bootProperties.path + " ------ "+ bootProperties.port;
}
}
1.2, usando @ConfigurationProperties
Clase de propiedades de arranque
package com.demo.config;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
@Setter // lombok,生成set方法
@ConfigurationProperties(prefix = "server") // 配置属性类,并定制前缀
@Component // 因为@ConfigurationProperties不能把此类放到boot容器中,所以要配合@Componpent使用
public class BootProperties {
@Value("${web.images-path}")
public String path;
// 不使用@Value注解,需要保证:前缀+属性名=全路径。还需要此属性有对应的setter方法
// @Value("${server.port}")
public int port;
// 使用@Value注解则需要写全路径
}
clase de controlador
@RestController
public class HelloController {
@Autowired
private BootProperties bootProperties;
@RequestMapping("/test5")
public Object test5(){
return bootProperties.path + " ------ "+ bootProperties.port;
}
}
1.3, use Medio Ambiente
El entorno es una clase en SpringCore para leer archivos de configuración. Al inyectar esta clase en una clase usando @Autowired, puede usar su método getProperty para obtener el valor de un elemento de configuración.
@RestController
public class HelloController {
@Autowired
private Environment environment;
@RequestMapping("/test7")
public Object test7(){
return environment.getProperty("server.port");
}
}
1.4, leer el archivo de configuración personalizado
Utilice conocimientos previos para comprender el código siguiente.
Principalmente agregar nueva anotación @PropertySource
Cree un paquete de configuración, luego cree un SysProperties
package com.demo.config;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "sys")
@Component
@PropertySource("classpath:sys.properties")
@Getter
@Setter
public class SysProperties {
private String param1;
private String param2;
}
clase de controlador
@RestController
public class HelloController {
@Autowired
private SysProperties sysProperties;
@RequestMapping("/test6")
public Object test6(){
return sysProperties.getParam1()+sysProperties.getParam2();
}
}
En segundo lugar, SpringBoot implementa el proyecto de guerra en Tomcat9 y comienza el principio.
创建一个新项目
Agregue un módulo
y luego agregue dependencias en pom
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<finalName>passerby-war</finalName>
<plugins>
<plugin>
<!-- 打包插件 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Luego agregue la clase de controlador y una clase de inicio
y agregue un método en la clase de controlador
package com.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
@RequestMapping("/demo01")
public Object demo01(){
return "hello,war";
}
}
Comience a empaquetar
, busque esta ubicación en la carpeta
, encuéntrela, copie el paquete war que acaba de crear y luego copie el paquete war en
su ubicación de Tomcat , luego abra el directorio bin, busque startup.bat en él, ábralo y espere. para ejecutarlo y luego haga clic en Abrir la carpeta donde pegó el paquete war hace un momento, todo estará bien ahora, abra el navegador e intente
Si no entiendes nada puedes mandar un mensaje privado! ! !