Say what I said before
SSM: Spring + for SpringMVC + MyBatis.
The SSM framework combination is now the most popular backend framework combination. In this article, I want to use pure annotations to integrate these three frameworks. Of course, SpringMVC is part of Spring itself. There is no integration. So SSM sometimes I call myself SM. (Actually don’t care about the name, just listen to it).
Of course, we all know that SpringBoot is now available to do this easily. So this article is for students in the study of preparation, has been skilled in the use of SpringBoot big guy please detour.
Tips: Download the source code at the back.
hi! Let’s just do it
The weapons you need
- Learned Spring, SpringMVC and MyBatis framework
- The SSM framework is best integrated using XML
- You must know what Maven is, and you must know how to use Mavne
- To have a continuous pursuit of technology of the heart
- To love my nation, love our motherland ^_^
Forget it. Turn it round
Integrated thinking
First of all, we should have a clear idea of integration, the so-called SSM integration is actually the integration of MyBatis into Spring. At this time to consider MyBatis have what to complete?
After consideration, the overall idea is as follows:
- MyBatis needs the data source to go to Spring, that is, register the data source in Spring.
- MyBatis Mapper will be handed over to Spring using dynamic proxy generation. B: well… SqlSessionFactory configuration…
- Spring RootContent and WebContent are merged…. B: well…
OK! hands-on
[1] Create a project
Open your idea, configure Maven, create a new project, and create the required directories and packages. Like the screenshot below.
[2] Configure dependencies
Open the POM file and add the following configuration
For the version lock part, I’m using spring5.2.6 here. What are your plans?
<! -- Version lock --> <properties> <! - spring version - > < spring. Version > 5.2.6. RELEASE < / spring. Version > < project. Build. SourceEncoding > utf-8 </project.build.sourceEncoding> </properties>Copy the code
Add dependencies:
<dependencies>
<! -- Jar of Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<! Mysql 5.1.47 -->
<! -- If your database is MySQL8, please change the corresponding version -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<! -- MyBatisjar -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1 track</version>
</dependency>
<! -- MyBatis and Spring integration of third-party JAR files -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<! -- druid connection pool -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<! -- servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<! Provided by scope -->
<scope>provided</scope>
</dependency>
<!-- 处理JSON的jar文件 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
</dependencies>
Copy the code
Here’s another plugin:
<build> <! <resources> <resource> <directory> SRC /main/ Java </directory> <includes> <include>**/*.properties</include> <include>**/*.*</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.*</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <! Maven </groupId> <artifactId> tomcat7-plugin </artifactId> <version>2.2</version> <configuration> <port>8080</port> <path>/</path> <uriEncoding>UTF-8</uriEncoding> </configuration> </plugin> <! Plugins </groupId> <artifactId> Maven-compiler-plugin </artifactId> <version>3.1</version> < Configuration > <source>1.8</source> <target>1.8</target> <encoding> UTF-8 </encoding> </configuration> </plugin> </plugins> </build>Copy the code
[3] Two configuration classes
Add a RootConfig configuration that is used to create the root container. This class is equivalent to the Spring configuration file applicationContext.xml when it is consolidated using XML configuration files
package com.qidian.config; import com.alibaba.druid.pool.DruidDataSource; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.*; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; /** * @author () @componentScans ({) @componentscans ({) @componentscans ({) @ComponentScan(" com.qidia.service ")}) // This configuration is used to scan and load all mapper interfaces and XML files. You can also use @bean to inject MapperScannerConfigurer, which scans @mapperscan (" com.qidia.mapper "), to load resource files for the configuration of the database connection @PropertySource("classpath:db.properties") public class RootConfig { @Value("${jdbc.driver}") private String driverClass; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; DruidDataSource DataSource = new DruidDataSource(); druid DataSource DataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClass); dataSource.setPassword(password); dataSource.setUsername(username); dataSource.setUrl(url); return dataSource; Public SqlSessionFactoryBean SqlSessionFactoryBean (){SqlSessionFactoryBean Bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource()); / / entity bean category name package. SetTypeAliasesPackage (" com. Qidian. Bank pojo "); return bean; } / / into the transaction manager @ Bean public TransactionManager TransactionManager () {DataSourceTransactionManager TransactionManager = new DataSourceTransactionManager(); transactionManager.setDataSource(dataSource()); return transactionManager; }}Copy the code
This class inherits from WebMvcConfigurer and can add view parsers, static resource maps, interceptors, and more via the parent API. This configuration is mainly used to configure web-related content, scan controllers, and so on.
package com.qidian.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @componentScan (" com.qidia.controller ") // Add SpringMVC Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Override public void AddResourceHandlers (ResourceHandlerRegistry registry) {// Mapping of static resources registry.addResourceHandler("/**/*.html").addResourceLocations("/"); registry.addResourceHandler("/**/*.css").addResourceLocations("/"); registry.addResourceHandler("/**/*.js").addResourceLocations("/"); registry.addResourceHandler("/**/*.png").addResourceLocations("/"); registry.addResourceHandler("/**/*.jpg").addResourceLocations("/"); registry.addResourceHandler("/lib/**/*.*").addResourceLocations("/lib/"); registry.addResourceHandler("/**/*.json").addResourceLocations("/"); }}Copy the code
And don’t forget to add db.properties to resources
JDBC. Driver = com. Mysql. JDBC. JDBC driver. Url = JDBC: mysql: / / 127.0.0.1:3306 / bank? serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=Copy the code
Look at the situation now:
[4]RootWebApplicationContext and DispatcherServletWebApplicationContext
Hereinafter referred to as RootWebApplicationContext: RootContext, DispatcherServletWebApplicationContext: DispatcherServletContext.
WebApplicationContext extends ApplicationContext, which represents the Spring WebApplicationContext. RootContext is created by ContextLoaderListener. It holds beans (such as Services) for various non-Web components registered with Spring. After the RootContext is initialized, store it in the ServletContext for easy retrieval. You can see in the source code: the servletContext. SetAttribute (WebApplicationContext ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, enclosing context).
This is followed by the initialization of the DispatcherServletContext, which takes RootContext as its parent context (you can reference non-Web components in RootContext within DispatcherServletContext and not vice versa). , and then initialize Web-related components such as controllers, view resolvers, and so on. DispatcherServletContext is initialized and stores itself in the ServletContext.
WebApplicationContext and DispatcherServlet context initialization
Add a class to the main package that initializes the Web environment:
package com.qidian; import com.qidian.config.RootConfig; import com.qidian.config.WebConfig; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * @author */ public Class BankContextInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<? >[] getRootConfigClasses() {return new Class[]{rootconfig.class}; } @Override protected Class<? >[] getServletConfigClasses() {return new Class[]{webconfig.class}; } @override protected String[] getServletMappings() {return new String[]{"/*","*.action"}; }}Copy the code
Take a look at the location of this class:
[5] The corresponding mapper, Service and Controller were added for testing
Browser access:
Download source address: gitee.com/win-dk/SSM-…