SPRINGBOOT
1 getting started
1.1 specific process of springboot
1yaml configuration file
2 automatic assembly
3 integrated web framework
4 integrated database
5 distributed development Dubbo (rpc) zookeeper
6 swagger interface document
7 task scheduling
8 springSecurity : shiro
1.2 springCould
1. Microservices
2. Getting started with spring could
3 RestFul
4 eureka
5 Ribbon
feign
HyStrix
zuul routing gateway
SpringCloud config: git
1.3 what is micro service
MVC three-tier MVVM microservice architecture
Microservice: it is an architectural style and a combination of a series of small services. It can schedule and combine the required functions through http interworking.
2. Frame construction
2.1 idea creating springBoot project
1 create directly
2 create controller test after configuration
@RestController public class Mycontroller { @RequestMapping("/hello") public String h1(){ return "I'm dying"; } }
3 package into jar package
4 terminal call
java -jar bootpro-0.0.1-SNAPSHOT.jar
5 configuration file properties
#Change project port number server.port=8081 #Custom banner spring.banner.location=banner.txt
3 automatic assembly principle
3.1 principle of automatic assembly
The core dependencies are in the parent project, version management and resource filtering
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>
We do not need to specify the version when we introduce the springboot dependency, because there is a management repository in the parent pom
Starter:
<!--web rely on tomcat web. xml dispatcherServlet--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
We can introduce any function we need to use
You can configure the dependent version in the pom of the project:
<properties> <java.version>1.8</java.version> <mysql.version>5.*.*</mysql.version> </properties>
20210419 note:
3.2 main program
//The integration encapsulates the spring config annotation. This class is a spring boot application @SpringBootApplication public class BootproApplication { public static void main(String[] args) { //Load classes through reflection SpringApplication.run(BootproApplication.class, args) } }
Main program annotation
@SpringBootConfiguration //The spring configuration file is a configuration file that represents the configuration class whose current class is spring @EnableAutoConfiguration //automatic assembly //Annotation scan @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) //@Notes under SpringBoootConfiguration: (note that this class is a spring configuration class) @Configuration //Comments under EnableAutoConfigurations: @AutoConfigurationPackage //Auto configuration package @Import(AutoConfigurationImportSelector.class)//Import selector //@Comments under AutoConfigurationPackage @Import(AutoConfigurationPackages.Registrar.class)//Using register to batch import components into containers
/** * {@link ImportBeanDefinitionRegistrar} to store the base package from the importing * configuration. */ static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports { @Override public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { //Import all components under the specified package into the package where the main program is located by default register(registry, new PackageImports(metadata).getPackageNames().toArray(new String[0])); } @Override public Set<Object> determineImports(AnnotationMetadata metadata) { return Collections.singleton(new PackageImports(metadata)); } }
(AutoConfigurationImportSelector.class) import components to the container
The figure above shows all candidate configuration classes
Each autoconfiguration class corresponds to a properties class. Assign values to specific properties through yaml or properties. The called autoconfig class will generate objects required for program operation through @ Bean annotation and submit them to the spring ioc container for management (generate a template object)
List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) //This method obtains all components and loads files from meta info
From spring Read configuration from factories (classes to be loaded)
After reading all the configurations, open them on demand according to the conditional equipment rules. For example, the annotation on the class in the figure below can be loaded into the container only when there is an advice in the container, and can be added only after the aop dependency is added
Main program running process
SpringApplication
1. Judge whether the application class is an ordinary project or a web project
2 load all available initializer settings into initializers
3 find out all application listeners and set them in listener
5 infer and set the definition class of the main method and find the running main class
Note:
springBoot automatically scans the package where the main program is located and the components under all its sub packages. If you want to modify it, you can: @ SpringBootApplication(scanBasePackages = "com")
1. Spring boot loads all auto configuration classes first
2. Each automatic remark type takes effect according to conditions
The configuration class in effect will register the component with the container
Note summary:
Basic notes:
@configuration:
Configuration class
(proxyBeanMethods=true) the full development mode strictly abides by the spring constraint, and the bean is a singleton mode;
=false (lite) when getBean is not in singleton mode, the spring runtime will not check to increase efficiency.
@Configuration public class MyConfig { @Bean("kenan") public Student getStudent(){ return new Student(22,"Conan",1608); } @Bean("miao") public Pet getPet(){ return new Pet(); } }
@import:
@Import(user.class) creates a user type component in the container. The default component name is the full class name (package + class name)
@conditional:
Condition assembly, and component injection is performed when the condition is met
@ImportResources:
Import spring configuration file:
@ImportResources("classpath:**")
@ConfigurationProperties:
Configure binding
@PropertySource
Load the specified properties file (*. Properties) into the Spring Environment. Can cooperate with @ Value and
@ConfigurationProperties is used.
@PropertySource and @ Value
In combination, you can inject the attribute variable Value in the custom attribute file into the member variable annotated with @ Value of the current class.
@PropertySource and @ ConfigurationProperties
In combination, you can bind the property file to a Java class and inject the variable value in the property file into the member variable of the Java class
1 import dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency>
Class 2 Annotated:
@ConfigurationProperties(prefix = "mypet") public class Pet { private String species; private String name; }
3. Properties file:
mypet.species="cat" mypet.name="Mimi"
Usage:
1: @Component + @ConfigurationProperties
2 @ConfigutationProperties +EnableConfigurationProperties
@EnableConfigurationProperties(HelloServiceProperties.class)
4 yaml
4.1 yaml syntax
#yaml format configuration file server: port: 8081 #object student: name: Kenan age: 22 #Object inline writing person: {name: Kenan, age: 18} #array pets: - cat - dog - pig #Inline writing animals: [cat, dog, pig]
4.2 yaml attribute assignment
The value in yaml can be mapped to the bean one by one to inject value into the bean
<!--use configProperties Annotations need to import this dependency--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
@ConfigurationProperties(prefix = "person") public class Person { private String name; private int age; private Map maps; }
person: name: sama age: ${random.int} maps: {hobby: girl, like: game}
4.3 specifying profiles
Use the specified properties file
@PropertySource("classpath:kenan.properties")
name=Kenan
public class Dog { @Value("${name}") private String name; private int age; }
4.4 yaml placeholder expression
id: ${random.int} id2: ${random.uuid} say: ${dog.hello:hello}aa #If the dog before the colon If hello exists, call the value of hello. Otherwise, use the following value:
4.5 yaml loose binding
Hump and separator conversion
private String lastName;
person: last-name: sama
5 JSR303 verification
Verify the format of data at the back end
<!--Enable background data verification--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
@Validated public class Person { @Email(message = "Mailbox format error") private String name; private int age; private Map maps; }
default message [mailbox format error]; origin class path resource [application.yaml]:3:11
6 multi environment configuration
Four locations for configuration files
1 config folder under root directory:
2 root directory:
3. config under classpath:
Under 4 classpath:
Priority 1 "2" 3 "4
yaml multi environment configuration selection (spring profiles active)
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8yQL75kd-1627207396216)(K:\u\study \ document \ image boot schematic 6)]
server: port: 8081 spring: profiles: active: test --- server: port: 8082 spring: profiles: dev --- server: port: 8083 spring: profiles: test
7 Import static resources
Under webmvcoautoconfiguration
EnableWebMvcConfiguration
public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern) .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())) .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)); } }
What is webjars
Spring boot uses webjars to manage static resources uniformly
The dependency method is used to introduce commonly used web package libraries, such as jquery
<dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.6.0</version> </dependency>
1 the path to access static resources is / webjars/**
2 default path for accessing static resources / * * for example: / T1 Txt, you will go to the mapping directory corresponding to / * * to find T1 txt
<script src="webjars/jquery/3.4.1/jquery.js"></script> <--use webjar Reference static resources-->
/** * Path pattern used for static resources. */ private String staticPathPattern = "/**";
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" }; /** * Locations of static resources. Defaults to classpath:[/META-INF/resources/, * /resources/, /static/, /public/]. */
Generally, static places pictures, public places public js resources, and upload and download files
Three priorities r > s > p
3 customize the static resource location in the configuration file
spring: mvc: static-path-pattern: /mystaic/, classpath:/mystatic/
7.1 home page
private Resource getIndexHtml(String location) { return this.resourceLoader.getResource(location + "index.html"); }
Therefore, you must create a new index in the static resource folder html
8 thymeleaf
The default configuration class is configured with prefix and suffix
@ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
8.1 start
You can turn off the thymeleaf cache in yaml
spirng.thymleaf.cache: false
1 import dependency
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
/*The html under the template file can only be accessed through the controller * Template engine support is required*/ @Controller public class IndexController { @RequestMapping("/a") public String index(){ return "index"; } }
2. Import the namespace of the constraint declaration thymeleaf
<html lang="en" xmlns:th="http://www.thymeleaf.org">
Use th tag in element 3
<!--All elements can be html take over--> <div th:text="${msg}"></div>
8.2 basic grammar
<!--All elements can be html take over--> <div th:text="${msg}"></div> <!--Non escape string can be output html--> <div th:utext="${msg}"></div> <!--ergodic users It's a collection user Is a single element--> <h2 th:each="user:${users}" th:text="${user}"></h2> <!--Add an element between two brackets--> <h2 th:each="user:${users}"> [[${user}]] </h2>
//Tool classes can convert arrays into collections model.addAttribute("users", Arrays.asList("kenan","sama"));
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet"> <link th:href="@{/css/animate.css}" rel="stylesheet"> <link th:href="@{/css/style.css}" rel="stylesheet"> <link th:href="@{/css/login.css}" rel="stylesheet"> <script th:src="@{/js/jquery-3.4.1.min.js}"></script> <script th:src="@{/js/bootstrap.min.js}"></script>
9 extended MVC
9.1 extended MVC
Custom view parser
//Extended mvc @Configuration public class MyMVC implements WebMvcConfigurer { @Bean public MyViewResolver myViewResolver(){ return new MyViewResolver(); } //Self configured viewResolver class MyViewResolver implements ViewResolver{ @Override public View resolveViewName(String viewName, Locale locale) throws Exception { return null; } } }
//Adding a view jump page is equivalent to manually configuring the controller @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/user").setViewName("index"); }
9.2 interceptors
@Override public void addInterceptors(InterceptorRegistry registry) { //Add blocking links and blocking without blocking registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns(); }
10 consolidated database
10.1 springboot JDBC
1 set parameters
spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/graduation_project?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Hongkong driver-class-name: com.mysql.cj.jdbc.Driver
2. Use the JDBC template provided by spring to operate the database
@RestController public class MyController { @Autowired JdbcTemplate template; @RequestMapping("/test") public List<Map<String, Object>> t1(){ String sql = "select * from patients"; List<Map<String, Object>> maps = template.queryForList(sql); return maps; } }
@RequestMapping("update/{name}/{id}") public String update(@PathVariable("name") String name, @PathVariable("id") String id){ String sql = "update patients set p_name = ? where p_id = ?"; Object[] objects = new Object[2]; objects[0] = name; objects[1] = id; template.update(sql,objects); return "ok"; }
10.2 integrating druid data sources
1 import maven dependency
com.alibaba druid 1.1.222 specify the database type and configure the druid attribute
spring: datasource: username: root password: 123456 url: jdbc:mysql://localhost:3306/graduation_project?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Hongkong driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # Other configurations of data source initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true # Configure filters for monitoring statistics interception, stat monitoring interface sql statistics, 'wall' is used for firewall defense sql injection log4j log file filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3 create a druid configuration file to make it take effect. Although we have configured other properties of Druid connection pool, it will not take effect. Because the default is Java sql. Datasource class to get properties. Some properties are not available in datasource. If we want the configuration to take effect, we need to manually create the Druid configuration file.
//Bind druiddata source parameter @ConfigurationProperties("spring.datasource") @Bean public DataSource dataSource(){ return new DruidDataSource(); } //Configure background monitoring and register a servlet @Bean public ServletRegistrationBean tatViewServlet() { ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); //Set background management users and some configurations HashMap<String, String> map = new HashMap<>(); map.put("loginUsername", "admin"); map.put("loginPassword", "123456"); //Set access white list map.put("allow", "localhost"); bean.setInitParameters(map); return bean; }
11 integrate Mybatis
Previously on:
When integrating mybatis in spring, mappercannerconfigurer can be used to implement the dynamic agent of mapper (the step of manually implementing mapper class "mapperinpl" is omitted), and the @ Repository annotation can also be omitted on the interface
<!--generate mapper proxy class--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zzuli.mapper"/> </bean>
public interface StuMapper { List<Student> getStu(); }
@mapper annotation
@Mapper is added to the mapper interface in spring boot to generate the corresponding interface implementation class at compile time
@MapperScan
Add the interface in the specified package to the startup class of springboot, and the corresponding implementation class will be generated after compilation
11.1 introduction
1. Introduce maven dependency
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.32. Write mapper
@Mapper public interface PatientMapper { List<Patient> getPat(); Patient getPatById(String id); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="zuli.kenan.boot_mybatis.mapper.PatientMapper"> <select id="getPat" resultMap="patMap"> select * from patients </select> <!--Result set--> <resultMap id="patMap" type="zuli.kenan.boot_mybatis.pojo.Patient"> <result property="id" column="p_id"/> <result property="name" column="p_name"/> <result property="password" column="password"/> </resultMap> </mapper>
#Integrate mybatis mybatis: type-aliases-package: zuli.kenan.boot_mybatis.pojo mapper-locations: classpath*:mapper/*.xml
@MapperScan("com.kenan.mybatisboot.mapper")
12 SpringSecurity
Functional authority
Access rights
Menu permissions
Interceptor filters are required to be native code
12.1 framework construction
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //Chain call builder mode //Specify access policy //The function page corresponding to the home page can only be accessed by people with corresponding permissions //url followed by parameter * can only be accessed when the parameter is consistent with the rules in hasrole http.authorizeRequests().antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2"); //After the access is blocked, it will jump to the login page (self-contained) he most basic configuration defaults to automatically generating a login page at // * the URL "/login", redirecting to "/login?error" for authentication failure. http.formLogin(); } //The authenticated user assigns the corresponding role to the specified user. To set the password code, do not use the plaintext password // enable in memory based authentication with a user named // * // "user" and "admin" // * .inMemoryAuthentication().withUser("user").password("password").roles("USER").and() // * .withUser("admin").password("password").roles("USER", "ADMIN"); // * } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("kenan").password("1234").roles("v1","v2") .and() .withUser("kenan").password("22").roles("v3"); } }
13 Shiro
);
//After the access is blocked, it will jump to the login page (self-contained) he most basic configuration defaults to automatically generating a login page at // * the URL "/login", redirecting to "/login?error" for authentication failure. http.formLogin(); } //The authenticated user assigns the corresponding role to the specified user. To set the password code, do not use the plaintext password // enable in memory based authentication with a user named // * // "user" and "admin" // * .inMemoryAuthentication().withUser("user").password("password").roles("USER").and() // * .withUser("admin").password("password").roles("USER", "ADMIN"); // * } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("kenan").password("1234").roles("v1","v2") .and() .withUser("kenan").password("22").roles("v3"); }
}
## 13 Shiro