The most popular Java Web framework is SSM, which is favored by many because it is lighter and more flexible. SpringBoot’s lightweight, simplified project configuration, and lack of XML configuration requirements are now gaining popularity

In this article, I will show you how to quickly build a Framework for Maven + Spring + SpringMVC + MyBatis + SpringBoot in Intellij Idea, so that you can start your Web project immediately

Attach the github address of sSM-Springboot for this simple framework build

I. Create a project

Choose the Spring Initiallizr

Add the most basic several rely on Web, MySQL, MyBatis, other requirements can be added later; MySQL is selected as the database

Configure the data source

The data source stores all the information needed to establish a database connection

1. Configure the IDEA data source

Enter address, port, username, password, etc

2. Configure the Spring data source

Application. Properties file adds:

spring.datasource.url = jdbc:mysql://xx.xx.xx.x:xxx/xxx? characterEncoding=utf8&allowMultiQueries=true&useSSL=false
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
Copy the code
  • Url: indicates the URL of the data sourceJDBC :mysql://Host: Post /DatabaseAllowMultiQueries = true: Allows multiple SQL queries to be executed at the same time (separated by semicolons). UseSSL: Indicates whether to enable SSL connections
  • Username: indicates the username
  • Password: password
  • Driver-class-name: indicates the driver name. Different databases have different Drivername, for example, oracle databaseoracle.jdbc.driver.OracleDriver, the MySQL database iscom.mysql.jdbc.Driver

3. Spring annotations

  • Annotate a Controller with the @Controller / @RestController annotation to indicate that the class exists as a role for the Controller
  • Annotate a business layer class with the @Service annotation
  • Annotate a persistent mapper interface with the @repository annotation
  • Annotate other components with the @Component annotation
  • Annotate the Configuration class with the @Configuration annotation

4. MyBatis

The most important part of the construction of the whole project is the integration of Springboot and Mybatis, and Springboot also provides a very convenient way.

1. The XML file

  • Declare as a mapping file
  • Namespace: indicates the mapping interface corresponding to the mapping file. Typically, an XML mapping configuration file corresponds to a namespace, which in turn corresponds to an interface
<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE mapper PUBLIC"- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.swit.dao.MyMapper">

</mapper>
Copy the code

2. application.properties

  • Mybatis configuration, which specifies the address of the Mybatis base configuration file and entity class mapping file
mybatis.mapperLocations = classpath:mapper/**/*.xml
mybatis.typeAliasesPackage = com.swit.model
Copy the code
  • Configuring typeAliasesPackage enables entity classes within the com.swit.model package to use aliases in mapping files, such as:
<select id="getUser" parameterType="int" resultType="User">

</select>
Copy the code

ResultType =” com.swit.model.user “if typeAliasesPackage is not configured, resultType=” com.swit.model.user”

  • If you want to configure MyBatis via an XML file, add the file path:
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
Copy the code

3. Add a scan for mapper

You can do one of two things

(1) Optionally add @mapperscan to the startup class

Value is the package in which the Mapper class resides.

@MapperScan(value = "com.swit.dao")
Copy the code

In addition, the @Mapperscan annotation is for interface classes, so any annotated interface class needs to be scanned through this annotation

(2) You can add @mapper annotations to each mapper class

@Mapper
@Repository
public interface MyMapper {
}
Copy the code

Now that you’ve built your project, I’ll cover a few more things.

Five. Other points to note

1. @SpringBootApplication

  • This annotation is in the startup class
  • @SpringBootApplication is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with the default properties, so the bootstrap class doesn’t need to add these three annotations
  • @Configuration: Marks a class as a Configuration class.
  • @enableAutoConfiguration: Enables automatic configuration.
  • @ComponentScan: Automatically collects all Spring components

2. Deploy the server

If you want to deploy your SpringBoot project to Aliyun, Tencent Cloud and other servers, then you need to add something. 1. If you need to through the way of packaging for deployment in the web container, you will need to inherit SpringBootServletInitializer covering the configure (SpringApplicationBuilder) method

public class SpringbootApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { // Note that you point to the Application launcher class that was originally executed with the main methodreturnbuilder.sources(SpringbootApplication.class); }}Copy the code

2. Add packaged plug-ins to POM files

<build> <! -- Packaged project name, <groupId> org.springFramework.boot </groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> < artifactId > maven -- the compiler plugin < / artifactId > < version > 3.1 < / version > < configuration > <! Set the JDK version to use at compile time --> <source> 1.8 < /source> <! --> <target>1.8</target> <! - set totrueSkip the test --> <skip>true</skip>
				</configuration>
			</plugin>
		</plugins>
	</build>
Copy the code
  1. You’ll probably need to do some cross-domain processing
@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", Origin);
        response.setHeader("Access-Control-Allow-Methods"."POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age"."3600");
        response.setHeader("Access-Control-Allow-Headers"."Origin, X-Requested-With, Content-Type, Accept, " + this.tokenHeader);
        response.setHeader("Access-Control-Allow-Credentials"."true");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {}}Copy the code

Integrate other components

1. redis

Redis is also the NoSQL that we use a lot in our projects, often for caching things.

Rely on

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Copy the code

application.properties

# Redis database index (default 0)
spring.redis.database=0
# Redis server addressSpring. Redis. Host = 127.0.0.1# Redis server connection port
spring.redis.port=6379
# Redis server connection password (default null)
spring.redis.password=123456
# maximum number of connections in the pool (use negative values to indicate no limit)
spring.redis.pool.max-active=15
Maximum connection pool blocking wait time (negative value indicates no limit)
spring.redis.pool.max-wait=-1
The maximum number of free connections in the connection pool
spring.redis.pool.max-idle=15
Minimum free connection in connection pool
spring.redis.pool.min-idle=0
Connection timeout (ms)
spring.redis.timeout=0
Copy the code

Druid data source

DB connection pool for monitoring

Rely on

<dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid</artifactId>
       <version>1.0.20</version>
</dependency>
Copy the code

application.properties

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters=stat
spring.datasource.maxActive=20
spring.datasource.initialSize=5
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxOpenPreparedStatements=20
Copy the code

Your attention is my biggest motivation to write blog ~

What do you like?

  • You have to figure out String, StringBuilder, StringBuffer
  • Share some personal nuggets from the Java back end
  • Teach Shiro to integrate SpringBoot and avoid various potholes
  • Shiro + SpringBoot integration JWT