Spring Boot study notes (ultra-detailed)

A, spring boot entry

1, Spring Boot Profile

A simplified framework for Spring application development;
a large integration of the entire Spring technology stack;
the J2EE developers a one-stop solution;

2, micro-services

2014,martin fowler

Micro services: architectural style (micro-based service)

An application should be a set of small service; can communicate via HTTP way;

Monomers Used: ALL IN ONE

Micro-services: Each functional element is an independent final alternative upgrade and software independent unit;

3, environment preparation

Environmental constraints

-jdk1.8: Spring Boot recommended jdk1.7 and above; java version "1.8.0_112"

-maven3.x: 3.3 or later maven; Apache Maven 3.3.9 

–IntelliJIDEA2017:IntelliJ IDEA 2017.2.2 x64、STS

–SpringBoot 1.5.9.RELEASE:1.5.9;

Unified environment; 

1, MAVEN provided;

To the profiles of the label maven settings.xml configuration file to add

<profile>
  <id>jdk-1.8</id>
  <activation>
    <activeByDefault>true</activeByDefault>
    <jdk>1.8</jdk>
  </activation>
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
  </properties>
</profile> 复制代码

2, IDEA set

Integration maven come in;

4、Spring Boot HelloWorld

A function:

Hello browser sends a request, the server accepts and processes the request, response Hello World string;

1, create a maven project; (jar)

2, spring boot introduced related dependencies

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies> 复制代码

3, write a main program; launch applications Spring Boot

 /**
 *  @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
 */
@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) {

        // Spring应用启动起来
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }
} 复制代码

4, related to the preparation Controller, Service

@Controller
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World!";
    }
}  复制代码

5, the main program to run test

6, simplified deployment

 <!-- 这个插件,可以将应用打包成一个可执行的jar包;-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build> 复制代码

5, Hello World exploration

1, POM file

1, the parent project

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>

他的父项目是
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-dependencies</artifactId>
  <version>1.5.9.RELEASE</version>
  <relativePath>../../spring-boot-dependencies</relativePath>
</parent>
他来真正管理Spring Boot应用里面的所有依赖版本;  复制代码

Spring Boot version Arbitration Center;

After we import dependence is no need to write the default version; (there is no need to declare a natural version number which rely dependencies management)

2, starter

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency> 复制代码

spring-boot-starter-web:

spring-boot-starter: spring-boot scene initiator; help us introducing the assembly modules running web depends;

Spring Boot all the scenes are extracted features, one made of Starters (initiator), are dependent only need to introduce all of these scenarios associated starter introduced in coming projects inside. What is the function to use it to import the starter what scene 

2, of the main program, the main entrance class

/**
 *  @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot应用
 */
@SpringBootApplication
public class HelloWorldMainApplication {

    public static void main(String[] args) {

        // Spring应用启动起来
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }
}  

复制代码

@ SpringBootApplication : the Spring marked the Boot application instructions on a class of this class is the main class configuration of SpringBoot, SpringBoot should run the main method of this class to start SpringBoot application;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
      @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication { 复制代码

@ SpringBootConfiguration : the Spring of the Boot configuration class;

Marked on a class, he said it was a Spring Boot configuration class;

@ The Configuration : configuration class marked up this comment;

----- profile configuration class; configuration class is a container assembly; @Component

@ EnableAutoConfiguration : turn on auto-configuration feature;

Things before we need to configure, Spring Boot to help us to automatically configure; @ EnableAutoConfiguration tell SpringBoot open the automatic configuration capabilities; the automatic configuration to take effect;

@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration { 复制代码

@AutoConfigurationPackage: automatic configuration packet @Import (AutoConfigurationPackages.Registrar.class): 

Spring bottom notes @Import, the vessel is introduced into a component; component introduced by AutoConfigurationPackages.Registrar.class;

Where all components of all primary package configuration class (@SpringBootApplication class label) and the lower sub-packets of scanned Spring container inside;

@Import(EnableAutoConfigurationImportSelector.class);

Import component to the container?

EnableAutoConfigurationImportSelector: which introduced the selector assembly;

All of the components needed to return the introduced full class name manner; these components will be added to the container;

It will give a lot of container imported automatic configuration class (xxxAutoConfiguration); this scenario is to import all the components required for container and configure these components;

With automatic configuration class, eliminating the need to manually write the configuration we inject functional components like work; SpringFactoriesLoader.loadFactoryNames (EnableAutoConfiguration.class, classLoader) == Spring Boot at startup from the META-INF class path / spring. factories EnableAutoConfiguration get the value specified, these values ​​as auto-configuration classes into the container, the class will take effect automatically configured for automatic configuration to work for us; what we need before == own configuration, automatic configuration class to help us; J2EE overall integration solutions and automatic configuration are spring-boot-autoconfigure-1.5.9.RELEASE.jar in; 

6, Spring Boot quickly create a project using the Spring Initializer

1, IDEA: quickly create a project using Spring Initializer

IDE support the creation wizard to quickly create a project using Spring Spring Boot project;

Select the module we need; networking wizard to create a Spring Boot project; 

The default generated Spring Boot project; 

  • The main program has generated good, we just need our own logic
  • resources folder in the directory structure 
  • static: Save all static resources; js css images;
  • templates: Save all template pages; (Spring Boot default jar package using an embedded Tomcat, the default does not support JSP page); you can use a template engine (freemarker, thymeleaf);
  • application.properties:Spring Boot application configuration file; you can modify some of the default settings; 

2, STS quickly create a project using Spring Starter Project

Second, the configuration file

1, the configuration file

SpringBoot use a global configuration file, the configuration file name is fixed;

•application.properties

• application.yml

Profile role: Modify the default value SpringBoot auto-configuration; SpringBoot on the ground floor gave us automatically configured; 

Yamla (Yamla Is not Markup Language)

YAML A Markup Language: is a markup language  

YAML is not Markup Language: is not a markup language; 

Markup Language:

Previous profile; most of them are using xxxx.xml file;

YAML: data-centric than JSON, XML and other more suitable profile;

YAML: Configuration example

server:
  port: 8081 复制代码

​ XML:

<server>
	<port>8081</port>
</server> 复制代码

2, YAML syntax:

1, the basic grammar

k :( space) v: designates a pair of key-value pairs (there must be a space);

With spaces of indentation control hierarchy; as long as one is left-aligned data, are the same level

server:
    port: 8081
    path: /hello 复制代码

And attribute values ​​are case sensitive;

2, the value written

Literal: Common values ​​(numbers, strings, Boolean)

k: v: literally write directly;

No default string in single or double quotes;

"": Double quotes; there will not escape the string of special characters; special characters as themselves wish of intention

name: "zhangsan \ n lisi": Output; zhangsan wrap lisi

'': Single quote; will escape special characters, special characters ultimately is just a normal number of strings

name: 'zhangsan \ n lisi': output; zhangsan \ n lisi

Object, Map (attributes and values) (key-value pairs):

 k: v: the relationship between attributes and values ​​of an object to write the next line; note indentation

Object or k: v way

friends:
		lastName: zhangsan
		age: 20 复制代码

Inline wording:

friends: {lastName: zhangsan,age: 18} 复制代码

Array (List, Set):

Represents an element in the array values ​​- with

pets:
 - cat
 - dog
 - pig 复制代码

Inline wording

pets: [cat,dog,pig] 复制代码

3, the injection profile values

Profiles

person:
    lastName: hello
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists:
      - lisi
      - zhaoliu
    dog:
      name: 小狗
      age: 12 
复制代码

javaBean:

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
 *
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;  复制代码

We can import the configuration file processor, after writing configuration have prompted the

<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency> 复制代码

1, properties utf-8 default configuration file may be garbled in the idea of

Adjustment

2, @ Value acquisition value and acquisition value comparison @ConfigurationProperties


Profile yml or properties they can get to value;

If you say that we just need to get some business logic at a particular value in the configuration file, use @Value;

If we say that we wrote a javaBean dedicated to mapping and configuration files, we just use @ConfigurationProperties;

3, the injection profile data checksum value

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
    @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog; 
复制代码

4、@PropertySource&@ImportResource&@Bean

@ PropertySource : load the specified configuration file;

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
 *  @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;  复制代码

@ ImportResource : Importing Spring configuration file, so that the contents of the configuration file which is to take effect;

Spring Boot there is no Spring configuration file, write our own configuration files, it can not automatically identify;

Would like Spring configuration file to take effect, came loaded; @ ImportResource marked on a configuration class

@ImportResource(locations = {"classpath:beans.xml"})
导入Spring的配置文件让其生效 复制代码

Not to write the Spring configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans> 复制代码

SpringBoot recommended way to add components to a container; recommended way to use the full annotated

1, configuration class ** @ Configuration ** ------> Spring configuration file

2, ** @ Bean ** component is added to the vessel

/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
 *
 * 在配置文件中用<bean><bean/>标签添加组件
 *
 */
@Configuration
public class MyAppConfig {

    //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService02(){
        System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }
} 复制代码

To be continued. . .


Guess you like

Origin juejin.im/post/5deca71d518825123751b1aa
Recommended