SpringBoot advantages:

1. Remove a large number of XML configuration files

2. Simplify complex dependency management

3. Used together with various starter, automatic configuration can be basically achieved

4. Start the container quickly

5. It is easy to deploy and run Java-JAR with Maven or Gradle

6. It is easier to integrate Spring Cloud to realize microservices, which is more suitable for large projects

Create standalone Spring applications, embedded Tomcat and Jetty containers, no need to deploy WAR packages, simplify Maven and Gradle configuration, automate Spring configuration as much as possible, and directly integrate utility functions in the production environment, such as metrics, health checks, and extension configuration. No code generation or XML configuration required.

The transition of the SpringMVC project to Springboot mainly does the following

1. Profile configuration

2. Global variables are read in from the properties file

3. Configure the data source with Mybatis

4. Configure log files

5. WebConfig configuration (including the original web.xml and spring-mVC.xml)

6. Remove redundant bean injection

Profile configuration

In a traditional Spring project, multiple profiles are configured by first writing multiple profiles to the POM.xml file and then preloading the selected profile environment by executing a Maven file before starting the project. After loading, when executing the project, it will decide which.properties file to load into the global variable based on the loaded Environment.

Managing multiple profiles in Springboot is straightforward.

Profiles can be selected when the JAR package is run on the command line

java -jar example.jar –spring.profiles.active=test

Or in the global configuration of application.properties

Add spring.profiles. Active =test to application.properties

Both methods can launch the “test” profile, with the former taking precedence over the latter in execution.

(Incidentally, in Springboot, both of these methods are essentially “externalized configuration” to edit and replace the Environment.)

In addition, each individual profiles is configured in the “application-XXx. properties” format for each different environment, for example:

1. Application-pro. properties indicates the preview environment

2. Application-dev. properties indicates the development environment

3. Application-test. properties Indicates the test environment

When we need to test whether the profile is properly loaded, we can write it in the corresponding.properties file

server.port=9080

When you start up, you can see if the port has been started.

It is worth mentioning here in passing the order in which Springboot loads configuration files

1. The devTools global Settings property in the home directory (~/. Spring-boot-devtools. properties, if DevTools is active).

2. @testpropertysource annotations on test cases.

3. Annotation @springBoottest #properties on test case.

4. Command line parameters

5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in environment variables or system properties).

6. Set ServletConfig initialization parameters.

7. ServletContext initialization parameters.

8. JNDI properties from Java :comp/env

9. Java System properties (system.getProperties ()).

10. Operating system environment variables.

11. RandomValuePropertySource, contains only random. * the properties.

12. Profile-specific application properties (application-{Profile}. Properties and YAML variables) that are not typed into the JAR package.

13. Type profile-specific application properties (application-{Profile}. Properties and YAML variables) into the JAR package.

14. Application configurations (application.properties and YAML variables) that are not typed into the JAR.

15. Punch the application configuration (application.properties and YAML variables) into the JAR package.

16. @propertysource annotation on the @Configuration class.

17. The default attributes (use SpringApplication. SetDefaultProperties specified).

Global variables are read in from the properties file

The properties configuration for different environments is described in the previous section, where it describes how to write these properties to global variables for direct invocation elsewhere.

Public class examplePath {public static String examplePath; @Value(“${example_path}”) public void setExamplePath(String example) { Global.examplePath = examplePath; }}

By doing this, we’re going to add the.properties file

example_path=http://localhost:9090

This property is read into the global variable.

Data source configured with Mybatis

In a traditional Spring project, use Mybatis to connect to the database

1. First create a datasource bean

2. Then assemble the datasource into the SqlSessionFactory

3. Finally, assemble the SqlSessionFactory to MapperScannerConfigurer

This is all configured in an XML configuration file, which is a bit cumbersome. This XML configuration is avoided in Springboot as much as possible. Mybatis now provides support for Springboot, we just need to add Mybatis -spring-boot-starter dependency, it will do the following for us:

1. Automatically check the existing datasource

2. Create an instance of SqlSessionFactoryBean, SqlSessionFactory, and assemble the datasource

3. Create an instance of SqlSessionTemplate and assemble SqlSessionFactory into it

4. Automatically scan your Mapper, connect them to the SqlSessionTemplate, and register them with the Spring context so they can be injected into other beans.

So, in Springboot Mybatis configuration, we need to do the following things:

Fill in the application-{profile}.properties field with database information, for example:

spring.datasource.url=jdbcracle:thin//localhost:1234/example

spring.datasource.username=root

spring.datasource.password=123456

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver

spring.datasource.maxActive=10

spring.datasource.maxIdle=5

spring.datasource.maxWait=-1

In this way, we register the datasource bean in the Spring context.

Create a MybatisConfig file and replace XML with Java:

@Configuration @EnableTransactionManagement @MapperScan(“com.example.db.dao”) public class MybatisConfig { @Autowired private DataSource dataSource; @Bean(name = “sqlSessionFactory”) public SqlSessionFactory sqlSessionFactoryBean() { SqlSessionFactoryBean sqlsession = new SqlSessionFactoryBean(); sqlsession.setDataSource(dataSource); Try {/ / add the XML directory ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver (); sqlsession.setMapperLocations(resolver.getResources(“classpath:mapping/*.xml”)); return sqlsession.getObject(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean public PlatformTransactionManager annotationDrivenTransactionManager() { return new DataSourceTransactionManager(dataSource); } @Bean(name = “exampleSequence”) public OracleSequenceMaxValueIncrementer exampleSequenceBean(){ OracleSequenceMaxValueIncrementer exampleSequence = new OracleSequenceMaxValueIncrementer(); exampleSequence.setIncrementerName(“EXAMPLE_SEQ”); exampleSequence.setDataSource(dataSource); return exampleSequence; }}

MapperScan is to scan the mapper under this package.

Create a mapping folder under the Resource folder and put it under it.

The function here is similar to that of XML, in that the traditional XML representation is represented in a.java file, essentially injecting the datasource step by step.

Because the example uses an Oracle database, the last exampleSequence demonstrates how to add a sequence.

Interface annotation @mapper for all mapper

Such as:

@Mapper

public interface UserMapper {



}

Log File Configuration

Logback supports configuration externalization in the form of properties, but for more detailed configurations, XML configuration is preferred.

In order for the XML file to read some static configuration like paths from the.properties file that may need to be changed frequently, you need to configure it in logback-spring.xml

<property resource=”application.properties” />

<property name=”log.root.level” value=”${log.root.level}” />

<property name=”log.path” value=”${log.path}” />

<property name=”log.moduleName” value=”${log.module}” />

This way you can add the application

log.path=/home/logs/example

log.root.level=INFO

log.module=example

Read it into logback-spring. XML and call it.

WebConfig configuration

The main purpose of WebConfig is to replace web.xml and Spring-mVC.xml with some basic configuration.

1. About web.xml

A traditional Spring project configures a web. XML file that: When we run the WAR package in an application container (such as Tomcat), The container loads the filter, servlet, error-page, welcome-file-list, listener, context-param, resource-ref and other configurations based on web.xml .

Includes the ContextLoaderListener, which is loaded here, to automatically assemble the ApplicationContext configuration information when the container is started.

<listener>

< listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

< /listener>

This ApplicationContext is the core of Spring IOC (inherited from the BeanFactory), and all singleton beans are instantiated at this point. Also, a DispatcherServlet, which is important in SpringMVC, is loaded here and determines which XML file to configure the DispatcherServlet from.



SpringMVC


org.springframework.web.servlet.DispatcherServlet

contextConfigLocation classpath:spring-mvc.xml

1

true–> < /servlet>

2. About Spring-mVC.xml

Spring-mvc.xml is the SpringMVC configuration file where you can configure the beans we introduced that need to be customized, such as ViewResolver, multipartResolver, HTTP message converters, custom interceptors, and so on.

All of the above has nothing to do with Springboot, mainly in order to know and know why, if you are not interested in can not look.

Back to the Springboot configuration. Springboot has a saying, “convention over configuration,” which is to use convention as much as possible, rather than specific configurations (when special configurations are needed).

Spring-boot-starter-web includes a spring-boot-autoconfigure after introducing the “out of the box” dependency. With this dependency in place, you can use an @enableAutoCongiguration annotation. This annotation will guess the Spring configuration you need based on the imported dependencies and help you configure it. Since spring-boot-starter-web has been introduced, this annotation will configure the Web-related configuration.

In addition, the @SpringBootApplication annotation already includes an @enableAutoCongiguration annotation. So simply annotate @SpringBootApplication on the bootstrap ExampleServerApplication class to automatically configure the Web configuration.

Of course, there may be some special configurations that we can create a WebConfig to customize

@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List

> converters) { converters.add(marshallingHttpMessageConverter()); } public MarshallingHttpMessageConverter marshallingHttpMessageConverter(){ MarshallingHttpMessageConverter marshallingHttpMessageConverter = new MarshallingHttpMessageConverter(); List

mediaTypes = new ArrayList

(); mediaTypes.add(MediaType.TEXT_XML); mediaTypes.add(MediaType.APPLICATION_XML); XStreamMarshaller xStreamMarshaller=new XStreamMarshaller(); marshallingHttpMessageConverter.setSupportedMediaTypes(mediaTypes); marshallingHttpMessageConverter.setMarshaller(xStreamMarshaller); marshallingHttpMessageConverter.setUnmarshaller(xStreamMarshaller); return marshallingHttpMessageConverter; } @bean (name = {“multipartResolver”}) public multipartResolver multipartResolver(){CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver(); commonsMultipartResolver.setDefaultEncoding(“utf-8”); commonsMultipartResolver.setMaxUploadSize(10485760000L); commonsMultipartResolver.setMaxInMemorySize(40960); return commonsMultipartResolver; @bean public ExceptionHandler exceptionResolver(){ExceptionHandler ExceptionHandler = new ExceptionHandler(); return exceptionHandler; } public void addInterceptors(InterceptorRegistry registry){registry. AddInterceptor (new) LogInterceptor()).addPathPatterns(“/**”); super.addInterceptors(registry); }}


>

The sample file I wrote does a few things:

1. Introduce an XML Http message converter

2. Introduce the multipartResolver

3. Introduce custom exception handlers

4. Introduce custom interceptors

Remove redundant bean injection

This is kind of a digression, but it’s one of the problems I actually run into.

While actually running the Springboot project, I found a few issues that wouldn’t go wrong in a traditional Spring project: redundant bean injection.

In a traditional Spring project, this is not an error, but in a Springboot project it is. My guess is that an error is reported when the class method name of the bean to be injected is relatively compact, and some beans are automatically configured by Springboot itself.

So, get rid of some beans that don’t need injection.