Get to know SpringBoot in one article

Posted by theda on Fri, 31 Jan 2020 02:12:37 +0100

Write before
I should have gone to Hangzhou on February 2nd to find a job, because the outbreak of the epidemic had to postpone my trip. Why not do anything at home?Better play games and watch movies than go out and brag with the interviewer.I first came into contact with SpringBoot in Black Malleyou Shop. Of course, this story tells you a different SpringBoot based on my own understanding and writing level of Cannot Repeat.Due to my limited level, there are different places for you to troubleshoot.

Learning Objectives

  1. What is SpringBoot
  2. Why Learn SpringBoot
  3. Getting Started with SpringBoot [To Give Up]
  4. SpringBoot Advanced [to Hair Loss]
  5. Research Principle

1. What is SpringBoot

1.1 Children's shoes who have studied SSM must know Spring, in fact, its full name is Spring Framework, which is also the hot Spring framework for interviews.This framework has been accompanied by the growth of a large number of java programmers. I have previously written a generic SSM empty project myself, hoping that each time I write a new project, I will copy the modifications directly without configuring them again.SSM shoe pairing should know a standard SSM project, matching files takes a lot of time, and configuration is only fine-tuned. To integrate other technical frameworks (such as velocity) and start configuration, will Spring solve this problem in 2020?Of course, we can think that people from other countries must have written the solution.

1.2 SpringBoot is a new framework to solve the above problems. In fact, it is not new either. After all, SpringBoot is an improvement based on the Spring Framework. In vernacular, SpringBoot is a scaffold for building enterprise projects. The main purpose is to build large Spring projects and minimize the configuration of writing XML, get started, get started, and focus on industry.Transaction code writing.

1.3 Official Introduction, I will use my elementary school English to barely translate for you

2. Why Learn SpringBoot

2.1 For ($$) this is a reality, but from a technical point of view, it is to solve a problem or a business.We can say from JAVA, since JAVA is active on the Internet platform, no one dares to question the advantages of this language, such as GC mechanism, object-oriented features, etc. But many peer languages such as PHP, Python also have a voice in the Internet industry.JAVA goes PHP instead. Python always say that Java is too bulky and cumbersome. They may have already written their functions. We are still building projects, writing xml, and managing the interdependencies of various libraries. Once the dependency problem arises, you will start to have a headache solving the dependency problem again. Otherwise, how can we say that JAVA code is compiled once and misnames are reported everywhere?

2.2 So SpringBoot appears, undoubtedly freeing JAVA programmers up their hands and investing more in unlimited overtime. What's more, it's better to invest in business functional requirements, so it's better to spend some time configuring XML than learning SpringBoot.

3. Get started with SpringBoot [to give up]

Here we use SpringBoot to quickly set up the SSM and complete the CRUD operation.Only queries are available in this article, Demo is complete.
Use JAVA environment JDK1.8, integration tool IDEA2018.3, maven3.5+.
There are two ways to build SpringBoot, one built by maven itself and the other by Spring Initializr.Let's use the first method here, and the second mindless way to experience it yourself.

3.1 Create an empty maven project NEXT without using the maven skeleton

3.2 Fill in the project coordinates NEXT

3.3 Fill in the Project Location Finish, if there is a pop-up box direct point OK

3.4 Final project structure

3.5 Add dependencies. Now our project has no semi-monetary relationship with SpringBoot. Traditional SSM s often have dependency conflicts. SpringBoot provides a parent project to specifically manage dependencies and versions. Just specify the parent project and ask you how cool you are without worrying about all kinds of dependencies.
Modify pon.xml

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

3.6 Add a web launcher, solve the dependencies, and then solve the configuration problem. To build SSM, it is necessary to configure web.xml, application.xml, and so on.SpringBoot provides a variety of launchers, which provide various auto-configuration dependencies, with which you no longer have to write all kinds of XML.Note that we did not specify a version here, because the parent project is already managed, ask you how cool you are!

 <dependencies>
	<dependency>
	    <groupId>org.springframework.boot</groupId>
	    <artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

3.7 Writing startup classes without using Tomcat to run, how does SpringBoot start, remember how we first learned JAVA to run programs?And SpringBoot projects are usually packaged in jar packages.Don't ask me how I don't know the web container works, because it's embedded in these things, so you don't even have a chance to match Tomcat!

package net.csdn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

3.8 The next step is to familiarize ourselves with the SSM development process and write the Controller

package net.csdn.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){
        return "hello spring boot!";
    }
}

3.8 Running tests
console output

D:\DevelopFiles\Java\jdk1.8.0_231\bin\java.exe -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:D:\DevelopFiles\JetBrains\IntelliJ IDEA 2018.3.6\lib\idea_rt.jar=55957:D:\DevelopFiles\JetBrains\IntelliJ IDEA 2018.3.6\bin" -Dfile.encoding=UTF-8 -classpath D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\charsets.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\deploy.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\access-bridge-64.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\cldrdata.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\dnsns.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\jaccess.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\jfxrt.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\localedata.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\nashorn.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\sunec.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\sunjce_provider.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\sunmscapi.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\sunpkcs11.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\ext\zipfs.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\javaws.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\jce.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\jfr.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\jfxswt.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\jsse.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\management-agent.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\plugin.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\resources.jar;D:\DevelopFiles\Java\jdk1.8.0_231\jre\lib\rt.jar;D:\CSDNProjects\springboot-demo\target\classes;E:\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.2.4.RELEASE\spring-boot-starter-web-2.2.4.RELEASE.jar;E:\.m2\repository\org\springframework\boot\spring-boot-starter\2.2.4.RELEASE\spring-boot-starter-2.2.4.RELEASE.jar;E:\.m2\repository\org\springframework\boot\spring-boot\2.2.4.RELEASE\spring-boot-2.2.4.RELEASE.jar;E:\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.2.4.RELEASE\spring-boot-autoconfigure-2.2.4.RELEASE.jar;E:\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.2.4.RELEASE\spring-boot-starter-logging-2.2.4.RELEASE.jar;E:\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;E:\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;E:\.m2\repository\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;E:\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.12.1\log4j-to-slf4j-2.12.1.jar;E:\.m2\repository\org\apache\logging\log4j\log4j-api\2.12.1\log4j-api-2.12.1.jar;E:\.m2\repository\org\slf4j\jul-to-slf4j\1.7.30\jul-to-slf4j-1.7.30.jar;E:\.m2\repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;E:\.m2\repository\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;E:\.m2\repository\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar;E:\.m2\repository\org\yaml\snakeyaml\1.25\snakeyaml-1.25.jar;E:\.m2\repository\org\springframework\boot\spring-boot-starter-json\2.2.4.RELEASE\spring-boot-starter-json-2.2.4.RELEASE.jar;E:\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.10.2\jackson-databind-2.10.2.jar;E:\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.10.2\jackson-annotations-2.10.2.jar;E:\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.10.2\jackson-core-2.10.2.jar;E:\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.10.2\jackson-datatype-jdk8-2.10.2.jar;E:\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.10.2\jackson-datatype-jsr310-2.10.2.jar;E:\.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.10.2\jackson-module-parameter-names-2.10.2.jar;E:\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\2.2.4.RELEASE\spring-boot-starter-tomcat-2.2.4.RELEASE.jar;E:\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.30\tomcat-embed-core-9.0.30.jar;E:\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.30\tomcat-embed-el-9.0.30.jar;E:\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.30\tomcat-embed-websocket-9.0.30.jar;E:\.m2\repository\org\springframework\boot\spring-boot-starter-validation\2.2.4.RELEASE\spring-boot-starter-validation-2.2.4.RELEASE.jar;E:\.m2\repository\jakarta\validation\jakarta.validation-api\2.0.2\jakarta.validation-api-2.0.2.jar;E:\.m2\repository\org\hibernate\validator\hibernate-validator\6.0.18.Final\hibernate-validator-6.0.18.Final.jar;E:\.m2\repository\org\jboss\logging\jboss-logging\3.4.1.Final\jboss-logging-3.4.1.Final.jar;E:\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;E:\.m2\repository\org\springframework\spring-web\5.2.3.RELEASE\spring-web-5.2.3.RELEASE.jar;E:\.m2\repository\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;E:\.m2\repository\org\springframework\spring-webmvc\5.2.3.RELEASE\spring-webmvc-5.2.3.RELEASE.jar;E:\.m2\repository\org\springframework\spring-aop\5.2.3.RELEASE\spring-aop-5.2.3.RELEASE.jar;E:\.m2\repository\org\springframework\spring-context\5.2.3.RELEASE\spring-context-5.2.3.RELEASE.jar;E:\.m2\repository\org\springframework\spring-expression\5.2.3.RELEASE\spring-expression-5.2.3.RELEASE.jar net.csdn.MainApplication

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-01-29 14:14:46.356  INFO 6400 --- [           main] net.csdn.MainApplication                 : Starting MainApplication on chenxinchen-PC with PID 6400 (D:\CSDNProjects\springboot-demo\target\classes started by chenxinchen in D:\CSDNProjects\springboot-demo)
2020-01-29 14:14:46.362  INFO 6400 --- [           main] net.csdn.MainApplication                 : No active profile set, falling back to default profiles: default
2020-01-29 14:14:47.319  INFO 6400 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-01-29 14:14:47.329  INFO 6400 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-01-29 14:14:47.329  INFO 6400 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-01-29 14:14:47.403  INFO 6400 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-01-29 14:14:47.403  INFO 6400 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 996 ms
2020-01-29 14:14:47.568  INFO 6400 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-01-29 14:14:47.747  INFO 6400 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-01-29 14:14:47.750  INFO 6400 --- [           main] net.csdn.MainApplication                 : Started MainApplication in 2.36 seconds (JVM running for 4.332)

The following information is available

  1. SpringBoot started successfully
  2. Using a web container is Tomcat
  3. Listening port is 8080

Use a browser to access: http://localhost:8080/hello
Browser appears

hello spring boot!

It means we've successfully built a web project with SpringBoot, so it's cool!

4.SpringBoot Advanced [to Hair Loss]

We have not written any XML to complete the Spring Spring MVC project. One word is cool, two words are fast and efficient!Next we'll continue with SpringBoot and integrate Mybatis, you'll be strong enough to lose your hair!

4.1 Connecting to databases in previous SSM projects required database drivers, connection pools, and mybatis frameworks, which are also needed in Springboot.SpringBoot default support for connection pools is pursuit, because technology nb, ask again is the provisioning of love!I'm too lazy to write SQL, so using generic Mapper technology, readers of generic mappers and optical connection pools can learn by themselves.

<!--Database Driver-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--Tracer Connection Pool,Is Universal mapper Integrate-->
<!--mybatis,Is Universal mapper Integrate-->
<!--currency mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.0.3</version>
</dependency>

4.2 Database here I use data from SpringBoot when my teacher was in Black Malleu

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `tb_user`
-- ----------------------------
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` tinyint(1) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'Liulite', '123456', '21', '0', '2019-12-30 19:20:43', '2019-12-30 19:20:47');
INSERT INTO `tb_user` VALUES ('2', 'Liu Yifei', '123456', '18', '0', '2020-01-01 20:30:38', '2020-01-01 20:30:42');
INSERT INTO `tb_user` VALUES ('3', 'Li Bingbing', '123456', '17', '0', '2020-01-01 20:31:15', '2020-01-01 20:31:19');

4.3 YAML Configuration, although SpringBoot advocates no configuration, it is impossible for a project to connect to a database without configuring the 4 elements of the database. SpringBoot is not as strong as any library you use. It knows that SpringBoot invented the YAML configuration, which is similar to XML, but more advanced and concise than XML, and interested children's shoes can Baidu themselves.
Add application.yaml to resources

server:
  port: 8080 # tomcat port
logging:
  level:
    net.csdn: debug # Log Level
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/yun1?serverTimezone=UTC
    username: root
    password:
mybatis:
  configuration:
    map-underscore-to-camel-case: true # Automatic hump matching
  type-aliases-package: net.csdn.demo.entity # alias

4.4 Add a comment @MapperScan("net.csdn.demo.mapper") to the startup class to scan the Mapper package (if familiar)

package net.csdn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("net.csdn.demo.mapper")
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

4.5 Following is the familiar SSM development process, adding entity classes, Mapper interfaces, Service classes, and finally Controller classes, note that Mapper uses the generic Mapper here.

package net.csdn.demo.entity;

import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;

@Table(name = "tb_user")
public class User {
    @Id
    @KeySql(useGeneratedKeys = true)
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private Boolean sex;
    private Date birthday;
    private Date createTime;
    @Transient
    private String note;
    //TODO Omits GET AND SET
}

package net.csdn.demo.mapper;

import net.csdn.demo.entity.User;
import tk.mybatis.mapper.common.Mapper;

public interface UserMapper extends Mapper<User> {
}

package net.csdn.demo.service;

import net.csdn.demo.entity.User;

import java.util.List;

public interface IUserService {
    List<User> queryAllUser();
}
----------------------------------------------------------------------------
package net.csdn.demo.service.impl;

import net.csdn.demo.entity.User;
import net.csdn.demo.mapper.UserMapper;
import net.csdn.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> queryAllUser() {
        return userMapper.selectAll();
    }
}

package net.csdn.demo.controller;

import net.csdn.demo.entity.User;
import net.csdn.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    @Autowired
    private IUserService userService;
    @GetMapping("/users")
    public List<User> queryAllUser(){
        return userService.queryAllUser();
    }
}

4.6 Start the main method and enter it in the browser http://localhost:8080/users If the information for the three people in the database appears, the mybatis framework has been successfully integrated.OMG is so effortless that individual enterprise projects are built with just a few configurations in one project.

[{"id":1,"username":"Liuyan","password":"123456","age":21,"sex":false,"birthday":"2019-12-30T19:20:43.000+0000","createTime":"2019-12-30T19:20:47.000+0000","note":null},{"id":2,"username":"Liu Yifei","password":"123456","age":18,"sex":false,"birthday":"2020-01-01T20:30:38.000+0000","createTime":"2020-01-01T20:30:42.000+0000","note":null},{"id":3,"username":"Li Bingbing","password":"123456","age":17,"sex":false,"birthday":"2020-01-01T20:31:15.000+0000","createTime":"2020-01-01T20:31:19.000+0000","note":null}]

5. Research Principles

5.1 We would then wonder why SpringBoot was so amazing that the use of SSM configurations in previous development has basically been wiped out.So how does SpringBoot auto-configure?Here we'll look at SpringBoot auto-configuration principles.SpringBoot startup is based on a startup class, which must have a lot of articles.

package net.csdn;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

We can see two special things

  • @SpringBootApplication
  • SpringApplication.run(MainApplication.class,args);

5.2 Follow up on the @SpringBootApplication source and find that there are three other comments we don't know

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan
@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 {
// Omit the unimportant here
}

5.3 @SpringBootConfiguration comes to the end with the @Configuration annotation, which is a configuration annotation that turns a class into an XML-like effect.The @SpringBootConfiguration annotation, on the other hand, is a SpringBoot-specific configuration annotation that can only be used by one application. Custom configurations use the @Configuration annotation.I don't post the source code here and am interested in reading it myself.
5.4 @EnableAutoConfiguration This comment reads the meaning of this comment from the name to turn on AutoConfiguration, to make it clear that the dot is the AutoConfiguration switch, to turn on AutoConfiguration in the Spring application context, to guess how you configure Spring, usually based on your class path or custom bean s.Take a chestnut and add the tomcat.jar package under the class path. You may need something TomcatServletWebServerFactory.Let's just go and see what's under your classpath and configure it for you.

 * Enable auto-configuration of the Spring Application Context, attempting to guess and
 * configure beans that you are likely to need. Auto-configuration classes are usually
 * applied based on your classpath and what beans you have defined. For example, if you
 * have {@code tomcat-embedded.jar} on your classpath you are likely to want a
 * {@link TomcatServletWebServerFactory} (unless you have defined your own
 * {@link ServletWebServerFactory} bean).

5.5 @ComponentScan We must have played SSM with component scanning before, SpringBoot we haven't, and how does Controller work, of course, is what this annotation does.Follow up on the source of this comment and you will see that the comment is already clear and clear. I'll translate it roughly: this comment is used in Spring XML beforecontext:component-scan Functionally, you specify the package to be scanned through the basePackageClasses or basePackages property, unless you specify to start the scan from the class package that declares this annotation.

 * Configures component scanning directives for use with @{@link Configuration} classes.
 * Provides support parallel with Spring XML's {@code <context:component-scan>} element.
 *
 * <p>Either {@link #basePackageClasses} or {@link #basePackages} (or its alias
 * {@link #value}) may be specified to define specific packages to scan. If specific
 * packages are not defined, scanning will occur from the package of the
 * class that declares this annotation.
 *
 * <p>Note that the {@code <context:component-scan>} element has an
 * {@code annotation-config} attribute; however, this annotation does not. This is because
 * in almost all cases when using {@code @ComponentScan}, default annotation config
 * processing (e.g. processing {@code @Autowired} and friends) is assumed. Furthermore,
 * when using {@link AnnotationConfigApplicationContext}, annotation config processors are
 * always registered, meaning that any attempt to disable them at the
 * {@code @ComponentScan} level would be ignored.

5.6 Overall @SpringBootApplication is to enable automatic configuration and component scanning. How can SpringBoot be automatically configured and where are those default configurations defined?We studied this run method and followed the source code very complex, but you took a look at it and I found it under the project classpath META-INF/spring.factories.This is something we definitely don't have in our project, but it was found in a dependency on spring-boot-autoconfigure, which is a stack of key-value configurations, with EnableAutoConfiguration followed by the configurations to load, where this jar package contains almost the configurations of mainstream frameworks, such as

  • redis
  • jms
  • amqp
  • jdbc
  • jackson
  • mongodb
  • jpa
  • solr
  • elasticsearch

5.7 We're familiar with opening WebMvcAutoConfiguration, we're only interested in the first few notes

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })

@Configuration Configuration Note
@ConditionalOnWebApplication Determines Project Type
@ConditionalOnClass determines if these byte codes are included
Here we understand that automatic configuration means conditional judgment
There is also a method note to understand

@ConditionalOnMissingBean
This annotation means that when we configure this bean, it automatically configures the invalidation

This article has ended the SpringBoot study here, of course, I will write a lot of details to supplement the knowledge of SpringBoot in the future. I hope you can make the New Year's weather better and have better technology!!

Published an original article. Praise 0. Visits 10
Private letter follow

Topics: Spring SpringBoot Java Tomcat