Home  >  Article  >  Java  >  Detailed introduction to springboot configuration annotations

Detailed introduction to springboot configuration annotations

不言
不言forward
2019-02-01 11:36:394411browse

This article brings you a detailed introduction to springboot configuration annotations. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Overview

Spring Boot is designed to simplify the initial construction and development process of new Spring applications. Spring Boot is not an enhancement to Spring's functionality, but provides a way to quickly use Spring.

2. Features

①Create independent Spring application
②Embedded Tomcat, no need to deploy WAR files
③Simplify Maven configuration
④Automatically configure Spring
⑤ Provides production-ready features such as indicators, health checks and external configuration
⑥ Works out of the box, no code generation, and no XML configuration required.

3. Annotation description

@SpringBootApplication The core annotation of the Spring Boot project, the main purpose is to enable automatic configuration;
@Configuration acts on the class, which is equivalent to an xml configuration file. Configuration Spring
@Bean acts on methods, which is equivalent to 60e23eb984d18edbb092da6b8f295aba
in xml configuration. @ComponentScan defaults to scanning the sibling directory of the class where @SpringBootApplication is located and its subdirectories.
@PropertySource("classpath:env.properties") reads the external configuration file and obtains the value through the @Value annotation
@Transactional declares the transaction

4. SpringBoot directory file structure explanation

src/main/java: Store code
src/main/resources
static: Store static files, such as css, js, image, (access method http://localhost:8080/js/main. js)
templates: Store static pages jsp, html, tpl
config: Store configuration files, application.properties

5. SpringBoot default loading file path

/META-INF/resources/
/resources/
/static/
/public/

SpringBoot default configuration

spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

6. Spring Boot hot deployment

①Add dependencies                                                                                                                    
#③idea set Auto-Compile, then Shift Ctrl Alt /, select Registry

Check compiler.automake.allow.when.app.running

④Files that are not hot deployed

1. /META-INF/maven, /META-INF/resources, /resources, /static, /public, or /templates
2. The specified file will not be hot deployed spring.devtools.restart.exclude=static/* *,public/**

3. Manually trigger restart spring.devtools.restart.trigger-file=trigger.txt

Change the code without restarting, control it through a text

7. Customization Start Banner

①Visit http://patorjk.com/software/taag/#p=display&h=3&v=3&f=4Max&t=itcast Spring Boot

②Copy the generated characters to a text file, and name the file banner.txt
③Copy banner.txt to the resources directory of the project

8. Global configuration file (application.properties or application.yml)

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>

For more clicks, please see the official website address


9. Starter pom


spring-boot-starter core Spring Boot starter, including automatic configuration support, logs and YAML

spring-boot-starter-amqp Support for advanced message queue protocols, implemented through spring-rabbit

spring-boot-starter-aop Support for aspect-oriented programming, including spring-aop and AspectJ

spring -boot-starter-data-elasticsearch Support for Elasticsearch search engine, including spring-data-elasticsearch

spring-boot-starter-data-jpa Support for Java persistence API, including spring-data-jpa, spring- orm and Hibernate
spring-boot-starter-jdbc Support for JDBC database
spring-boot-starter-redis Support for REDIS key-value data storage, including spring-redis
spring-boot-starter- data-redis
spring-boot-starter-security Support for spring-security
spring-boot-starter-test Support for common test dependencies, including JUnit, Hamcrest and Mockito, spring-test
spring -boot-starter-velocity Support for Velocity template engine
spring-boot-starter-activemq
spring-boot-starter-freemarker
spring-boot-starter-thymeleaf
spring-boot-starter -web supports full-stack web development, including Tomcat and spring-webmvc
spring-boot-starter-webflux
(See Baidu for more configurations)

10. Commonly used json frameworks

(1) JavaBean is serialized into Json, performance:

Jackson > FastJson > Gson > Json-lib

(2) Jackson processing related comments

The specified field is not returned: @JsonIgnore

Specify date format: @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT 8")
Empty fields are not returned: @JsonInclude(Include. NON_NUll)
Specify alias: @JsonProperty

11. SpringBoot uses task scheduling

(1)使用步骤:

①启动类里面 @EnableScheduling开启定时任务,自动扫描
②定时任务业务类 加注解 @Component被容器扫描
③定时执行的方法加上注解 @Scheduled(fixedRate=2000) 定期执行一次

(2)常用定时任务表达式配置和在线生成器

cron 定时任务表达式 @Scheduled(cron="*/1 * * * * *") 表示每秒

crontab 工具  https://tool.lu/crontab/

ixedRate: 定时多久执行一次(上一次开始执行时间点后xx秒再次执行;)
fixedDelay: 上一次执行结束时间点后xx秒再次执行
fixedDelayString:  字符串形式,可以通过配置文件指定

(3)异步定时任务

启动类里面使用@EnableAsync注解开启功能,自动扫描
定义异步任务类并使用@Component标记组件被容器扫描,异步方法加上@Async
①要把异步任务封装到类里面,不能直接写到Controller
②增加Futuref7e83be87db5cd2d9a8a0b8117b38cd4 返回结果 AsyncResultf7e83be87db5cd2d9a8a0b8117b38cd4("task执行完成");  
③如果需要拿到结果 需要判断全部的 task.isDone()

十二、SpringBoot拦截器、过滤器、监听器

(1)SpringBoot启动默认加载的Filter 

characterEncodingFilter
hiddenHttpMethodFilter
httpPutFormContentFilter
requestContextFilter

(2)Filter优先级

Ordered.HIGHEST_PRECEDENCE
Ordered.LOWEST_PRECEDENCE

(3)自定义Filter

1)使用Servlet3.0的注解进行配置
2)启动类里面增加 @ServletComponentScan,进行扫描
3)新建一个Filter类,implements Filter,并实现对应的接口
4) @WebFilter 标记一个类为filter,被spring进行扫描 
urlPatterns:拦截规则,支持正则
5)控制chain.doFilter的方法的调用,来实现是否通过放行
  不放行,web应用resp.sendRedirect("/index.html");
场景:权限控制、用户登录(非前端后端分离场景)等

(4)Servlet3.0的注解自定义原生Listener监听器

自定义Listener(常用的监听器 servletContextListener、httpSessionListener、servletRequestListener)
@WebListener

 public class RequestListener implements ServletRequestListener { 

@Override

public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
System.out.println("======requestDestroyed========");
}

@Override

public void requestInitialized(ServletRequestEvent sre) {
System.out.println("======requestInitialized========");
}

(5)自定义拦截器
1)implements WebMvcConfigurer
@Configuration

public class CustomWebMvcConfigurer implements WebMvcConfigurer  {

@Override

public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginIntercepter()).addPathPatterns("/api2/*/**");
//.excludePathPatterns("/api2/xxx/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
}

2)自定义拦截器 HandlerInterceptor
preHandle:调用Controller某个方法之前
postHandle:Controller之后调用,视图渲染之前,如果控制器Controller出现了异常,则不会执行此方法
afterCompletion:不管有没有异常,这个afterCompletion都会被调用,用于资源清理
3)按照注册顺序进行拦截,先注册,先被拦截

(6)对比

Filter是基于函数回调 doFilter(),而Interceptor则是基于AOP思想
Filter在只在Servlet前后起作用,而Interceptor够深入到方法前后、异常抛出前后等
Filter依赖于Servlet容器即web应用中,而Interceptor不依赖于Servlet容器所以可以运行在多种环境。
在接口调用的生命周期里,Interceptor可以被多次调用,而Filter只能在容器初始化时调用一次。
Filter和Interceptor的执行顺序:过滤前->拦截前->action执行->拦截后->过滤后

十三、两种部署方式jar和war

(1)jar包方式启动

添加maven插件,执行打包即可,启动命令:    java -jar **.jar &

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

(2)war包方式启动

a.在pom.xml中将打包形式 jar 修改为war  0d5281799fde01379a2f5b5ea0c57ee5warb381c39f05d1340a5f54760f38fa259d
b.添加构建项目名称 1079ce9524e93e3b51b338f3745023bdxdclass_springboot8bfec31baefed0960a447581fc9bf1d0
c.修改启动类

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

 d.打包项目,启动tomcat

十四、SpringBoot多环境配置

①不同环境使用不同配置
例如数据库配置,在开发的时候,我们一般用开发数据库,而在生产环境的时候,我们是用正式的数据
②配置文件存放路径
classpath根目录的“/config”包下
classpath的根目录下
③spring boot允许通过命名约定按照一定的格式(application-{profile}.properties)来定义多个配置文件  

The above is the detailed content of Detailed introduction to springboot configuration annotations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete