JAVA learning notes 24 - SpringBoot

Posted by fresch on Fri, 18 Feb 2022 05:05:19 +0100


Microservice architecture

Separate each functional element and dynamically combine the independent functional elements. Only the required functional elements can be combined. When more functional elements are needed, multiple functional elements can be aggregated. Therefore, the microservice architecture copies the functional elements instead of the whole application
Save call resources
The service of each functional element is a replaceable software code that can be upgraded independently


Spring boot dependencies: the core depends on the parent project
When we write or introduce some springboot, we don't need to specify the version, because there is a version warehouse
springboot startup scenario
springboot will turn all functional scenarios into initiators one by one
main program

// Mark this class as a springboot application
public class Springboot01HelloworldApplication {

    public static void main(String[] args) {
        // Start the springboot application, args);


// Configuration of springboot
	// @Configuration:spring configuration class
	// @Component: This is also a spring component
//Auto configuration
	// AutoConfigurationPackage: autoconfiguration package
	// @Import (autoconfigurationpackage. Register. Class): automatically configure package registration
	// @Import(AutoConfigurationImportSelector.class): automatically configure import selection
	// List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes); Get all configurations
    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
        List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
        Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
        return configurations;

SpringBoot starts from meta-inf / spring. In the classpath Get the value specified by EnableAutoConfiguration from factories
Import these values into the container as automatic configuration class, and the automatic configuration class will take effect to help us with automatic configuration;
The overall solution and automatic configuration of J2EE are in the jar package of springboot autoconfigure;
It will import many automatic configuration classes (xxxAutoConfiguration) into the container, that is, import all the components required for this scenario into the container and configure these components;
The automatic configuration class eliminates the need for us to manually write configuration injection function components;
1. Infer whether the type of application is a normal project or a Web project
2. Find and load all available initializers and set them in the initializers property
3. Find all the application listeners and set them in the listeners property
4. Infer and set the definition class of the main method, and find the running main class


Basic grammar

configuration file
SpringBoot uses a global configuration file with a fixed name
Syntax structure: key=value
Syntax structure: key: space value
Function of configuration file: modify the default value of SpringBoot automatic configuration, because SpringBoot is automatically configured at the bottom;

# Ordinary key value
name: ray

# object
  name: ray
  age: 24
# Inline writing
student: {name: ray,age: 24}

# array
  - Kobe
  - Jordan

player: [Kobe,Jordan]

Injection profile

  name: ray
  age: 18
  sex: true
  birth: 1998/1/1
  map: {k1: v1,k2: v2}
    - run
    - swim
    name: d
    age: 3
# Person{name='ray', age=18, sex=true, birth=Thu Jan 01 00:00:00 CST 1998, map={k1=v1, k2=v2}, list=[run, swim], dog=Dog{name='d', age=3}}

Loose binding
For example, the last name written in my yml is the same as lastName, and the letters followed by - are capitalized by default. This is loose binding.
It is the naming format of - used in yaml file and hump naming format used in java code. The two can match each other by themselves
JSR303 verification data
This is that we can add a layer of filter verification in the field to ensure the legitimacy of the data
Use annotation @ Validated on entity class
Then, in the attribute, for example, the @ Email annotation indicates that this attribute can only be mail format
There are many annotations inside it. In a word, it is to verify the legitimacy of the data
automatic assembly
1. SpringBoot boot will load a large number of auto configuration classes
2. Let's see if the functions we need are in the auto configuration class written by SpringBoot by default;
3. Let's see which components are configured in this automatic configuration class; (as long as the component we want to use exists in it, we don't need to configure it manually)
4. When adding components to the automatic configuration class in the container, some properties will be obtained from the properties class. We only need to specify the values of these attributes in the configuration file;
Xxxautoconfiguration: automatic configuration class; Add components to container
Xxxproperties: encapsulates the related properties in the configuration file;

Web development

Static resources

1. In springboot, we can handle static resources in the following ways
webjars localhost:8080/webjars/
public,static,/**,resources localhost:8080/
2. Priority Resources > static (default) > public

Thymeleaf template engine


The function of the template engine is that we write a page template. For example, some values are dynamic. We write some expressions. Where do these values come from? We encapsulate some data in the background. Then give the template and the data to our template engine. The template engine will help you parse and fill the expression to the position we specify according to our data, and then finally generate a content we want to write to us. This is the idea of our template engine, whether jsp or other template engines. It's just that the syntax may be a little different between different template engines.
Conclusion: as long as you need to use thymeleaf, you only need to import the corresponding dependencies. Put the html in the templates directory


<!DOCTYPE html>
<html lang="en"  xmlns:th="">
    <meta charset="UTF-8">
<!--All html Elements can be thymeleaf Nozzle: th: Yuan Su Ming-->
<div th:text="${msg}"></div>
public class IndexController {

    public String test(Model model) {
        return "test";


<!--All html Elements can be thymeleaf Nozzle: th: Yuan Su Ming-->
<div th:text="${msg}"></div>
<h3 th:each="user:${users}" th:text="${user}"></h3>
Simple expressions:(Expression syntax)
Variable Expressions: ${...}: Obtain variable value; OGNL;
    1),Get the properties and call methods of the object
    2),Use built-in basic objects:#18
         #ctx : the context object.
         #vars: the context variables.
         #locale : the context locale.
         #request : (only in Web Contexts) the HttpServletRequest object.
         #response : (only in Web Contexts) the HttpServletResponse object.
         #session : (only in Web Contexts) the HttpSession object.
         #servletContext : (only in Web Contexts) the ServletContext object.

    3),Some built-in tool objects:
      #execInfo : information about the template being processed.
      #uris : methods for escaping parts of URLs/URIs
      #conversions : methods for executing the configured conversion service (if any).
      #dates : methods for java.util.Date objects: formatting, component extraction, etc.
      #calendars : analogous to #dates , but for java.util.Calendar objects.
      #numbers : methods for formatting numeric objects.
      #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
      #objects : methods for objects in general.
      #bools : methods for boolean evaluation.
      #arrays : methods for arrays.
      #lists : methods for lists.
      #sets : methods for sets.
      #maps : methods for maps.
      #aggregates : methods for creating aggregates on arrays or collections.

  Selection Variable Expressions: *{...}: Select expressions: and ${}It is the same in function;
  Message Expressions: #{...}:  Get international content
  Link URL Expressions: @{...}: definition URL;
  Fragment Expressions: ~{...}: Fragment reference expression

      Text literals: 'one text' , 'Another one!' ,...
      Number literals: 0 , 34 , 3.0 , 12.3 ,...
      Boolean literals: true , false
      Null literal: null
      Literal tokens: one , sometext , main ,...
Text operations:((text operation)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(Mathematical operation)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(Boolean operation)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(Comparison operation)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:Conditional operation (ternary operator)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:
    No-Operation: _


brief introduction

SpringSecurity is the security framework for Spring project and the default technology selection of the underlying security module of SpringBoot. It can realize powerful Web security control. For security control, we only need to introduce the Spring boot starter security module and make a small amount of configuration to realize powerful security management
Related classes

  • Websecurityconfiguradapter: custom Security policy
  • AuthenticationManagerBuilder: custom authentication policy
  • @Enable WebSecurity: enable WebSecurity mode

The two main goals of spring security are authentication and authorization



Authentication: identity authentication, login, and verify whether the user has the corresponding identity;
Authorization: authorization, that is, permission verification. It verifies whether an authenticated user has a certain permission, that is, it determines whether the user can perform any operations, such as verifying whether a user has a certain role, or fine-grained verifying whether a user has a certain permission on a resource!
Session Manager: session management, that is, after the user logs in, it is the - session. Before exiting, all its information is in the session; The session can be an ordinary Java se environment or a Web environment;
Cryptography: encryption to protect the security of data. For example, the password is encrypted and stored in the database instead of plaintext;
Web Support: Web support, which can be easily integrated into the web environment;
Caching: caching, for example, after a user logs in, the user information, roles and permissions do not need to be checked every time, which can improve efficiency
Concurrency: Shiro supports concurrent verification of multithreaded applications, that is, if you start another thread in one thread, you can automatically transfer permissions
Broadcast it
Testing: provide test support;
RunAs: allow one user to access as another user (if they allow it);
Remember Me: Remember Me, this is a very common function, that is, after logging in once, you don't need to log in next time


Subject: the object that the application code directly interacts with is subject, that is to say, the core of Shiro's external API is subject. Subject represents the current user. This user may be a specific person. Anything interacting with the current application is subject, such as web crawler, robot, etc., and all interactions with subject will be delegated to SecurityManager; Subject is actually a facade, and securitymanager is
Actual executor
SecurityManager: Security Manager, that is, all security related operations will interact with SercurityManager, and it manages all subjects. It can be seen that it is the core of Shiro. It is responsible for interacting with other components of Shiro. It is equivalent to the role of dispatcher servlet of spring MVC
Real: Shiro obtains security data (such as users, roles and permissions) from real, which means that SecurityManager needs to obtain corresponding users from real for comparison to determine whether the user's identity is legal; You also need to get the user's corresponding roles and permissions from the Realm to verify whether the user's operations can be carried out. You can look at the Realm as a DataSource;
Subject: any user who can interact with the application;
Security Manager: equivalent to DispatcherSerlet in spring MVC; It is the heart of Shiro. All specific interactions are controlled through security manager. It manages all subjects and is responsible for authentication, authorization, session and cache management.
Authenticator: responsible for Subject authentication. It is - an extension point that can be customized; Authentication strategy can be used, that is, when the user has passed the authentication;
Authorizer: the authorizer, that is, the access controller, is used to determine whether the subject has permission to perform corresponding operations; That is, it controls the user's access to the application
Those functions of;
Realm: there can be - one or more realms, which can be considered as data sources of security entities, that is, those used to obtain security entities can be implemented in JDBC or memory, etc., which are provided by users; Therefore, generally, we need to implement our own realm in the application
Session manager: a component that manages the session life cycle. Shiro can be used not only in the Web environment, but also in the ordinary Java se environment
CacheManager: cache controller to manage the cache of users, roles, permissions, etc; Because these data are rarely changed, the performance of access can be improved after being put into the cache;
Cryptography: password module. Shiro improves some common encryption components for password encryption, decryption, etc


public class ShiroConfig {
    // ShiroFilterFactoryBean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        // Set up security manager

        // Add shiro's built-in filter
            anno: Access without authentication
            authc: Authentication is required to access
            user: I can only use it if I have it and remember it
            perms: You must have permission on a resource to access it
            role: You must have a role permission to access
        Map<String,String> filterMap = new LinkedHashMap<>();

        // Set login request

        return bean;
    // DefaultWebSecurityManager
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManage(@Qualifier("userRealm") UserRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // Associate UserRealm
        return securityManager;
    // Create a realm object
    public UserRealm userRealm() {
        return new UserRealm();

Topics: Java