Recently, I was telling students about the integration of Spring+Mybatis. According to some students’ comments, it is easier to understand the integration based on annotations. After all, no one in the team has completely abandoned configuration files for project development in the previous work. After all, no configuration is Spring’s official implementation, or why does SpringBoot exist
one Integrated thinking
1) Objective: to implement all configuration items in the configuration file without reservation by changing annotations and creating objects
2) provided by the Spring @ Bean @ Configuration @ ComponentScan @ EnableTransactionManagement @ EnableWebMvc etc. Need to know its meaning
two Create a Web project for Spring-MVC
1) Project Structure Directory:
No configuration is written in web.xml here
3. Create configuration classes and properties files respectively under the Config package
1. AppConfig.java
package com.bdqn.lyrk.ssm.study.app; import com.alibaba.druid.pool.DruidDataSource; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.io.IOException; /** * Spring Configuration class ** @author chen.nie * @date 2018/6/24 ** @configuration // indicates that this class is Configuration class @componentScan // Scan the custom components (repository service component controller) @ PropertySource (" classpath: application. The properties ") / / Read the application. The properties @ MapperScan (" com. BDQN. Lyrk. SSM. Study. App. Mapper ") / / scan Mybatis mapper interfaces @ EnableTransactionManagement / / open transaction management public class AppConfig {/ configuration data * * * * * @ date 2018/6/24 * * / @ Bean public DataSource dataSource(PropertiesConfig propertiesConfig) { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUsername(propertiesConfig.getUserName()); dataSource.setPassword(propertiesConfig.getPassword()); dataSource.setUrl(propertiesConfig.getUrl()); dataSource.setDriverClassName(propertiesConfig.getDriverClass()); return dataSource; } /** * Configure mybatis SqlSessionFactoryBean ** @param dataSource * @param propertiesConfig * @return */ @bean public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource, PropertiesConfig propertiesConfig) throws IOException { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setTypeAliasesPackage(propertiesConfig.getMybatisTypeAliasPackages()); / / dynamic access SqlMapper PathMatchingResourcePatternResolver classPathResource = new PathMatchingResourcePatternResolver (); sqlSessionFactoryBean.setMapperLocations(classPathResource.getResources(propertiesConfig.getMapperLocations())); return sqlSessionFactoryBean; } / * * * configuration of spring's declarative transaction @ return * * * / @ Bean public PlatformTransactionManager transactionManager (DataSource DataSource) { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource); return dataSourceTransactionManager; } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); return propertySourcesPlaceholderConfigurer; }}Copy the code
Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis
2.DispatcherConfig
1 package com.bdqn.lyrk.ssm.study.config; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.context.annotation.Bean; 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.web.servlet.config.annotation.EnableWebMvc; 7 import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 8 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 9 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 10 import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver; 11 import org.springframework.web.servlet.view.InternalResourceViewResolver; 12 import org.springframework.web.servlet.view.JstlView; 13 14 import java.util.Properties; 15 16 @Configuration 17 @EnableWebMvc 18 public class DispatcherConfig extends WebMvcConfigurerAdapter { 19 20 21 @Autowired 22 private PropertyConfig propertyConfig; 23 24 @Bean 25 public InternalResourceViewResolver internalResourceViewResolver() { 26 InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); 27 internalResourceViewResolver.setViewClass(JstlView.class); 28 internalResourceViewResolver.setPrefix(propertyConfig.getWebViewPrefix()); 29 internalResourceViewResolver.setSuffix(propertyConfig.getWebViewSuffix()); 30 return internalResourceViewResolver; 31} 32 33 34 * / * * set unified view of error handling to jump 35 * 36 * @ return 37 * / 38 @ beans 39 public SimpleMappingExceptionResolver simpleMappingExceptionResolver() { 40 SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver(); 41 Properties properties = new Properties(); 42 properties.getProperty("java.lang.Exception", "error"); 43 simpleMappingExceptionResolver.setExceptionMappings(properties); 44 return simpleMappingExceptionResolver; 49 * 50 * @param registry 51 */ 52 @override 53 public void addResourceHandlers(ResourceHandlerRegistry registry) { 54 registry.addResourceHandler(propertyConfig.getWebStaticHandler()).addResourceLocations(propertyConfig.getWebStaticResour ce()).setCachePeriod(propertyConfig.getWebStaticCachedPeriod()); 61 */ 62 @override 63 public void 61 */ 62 @override 63 public void 61 */ addInterceptors(InterceptorRegistry registry) { 64 super.addInterceptors(registry); 66 65}}Copy the code
Here you configure the View parser for SpringMVC, static resources, and so on, using the same code in the configuration file
3.PropertiesConfig
package com.bdqn.lyrk.ssm.study.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration @PropertySource("classpath:application.properties") public class PropertyConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.driver}") private String driver; @Value("${spring.datasource.user}") private String user; @Value("${spring.datasource.password}") private String password; @Value("${spring.web.view.prefix}") private String webViewPrefix; @Value("${spring.web.view.suffix}") private String webViewSuffix; @Value("${spring.web.static.handler}") private String webStaticHandler; @Value("${spring.web.static.resource}") private String webStaticResource; @Value("${spring.web.static.cache.period}") private Integer webStaticCachedPeriod; @Value("${mybatis.type.alias.package}") private String mybatisTypeAliasPackage; public String getWebViewPrefix() { return webViewPrefix; } public String getWebViewSuffix() { return webViewSuffix; } public String getWebStaticHandler() { return webStaticHandler; } public String getWebStaticResource() { return webStaticResource; } public Integer getWebStaticCachedPeriod() { return webStaticCachedPeriod; } public String getMybatisTypeAliasPackage() { return mybatisTypeAliasPackage; } public String getUrl() { return url; } public String getDriver() { return driver; } public String getUser() { return user; } public String getPassword() { return password; } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); }}Copy the code
This is used to read the contents of the application.properties file. Note the meaning of @Value and @propertysource
4.MyWebAppInitializer
1 package com.bdqn.lyrk.ssm.study.config; 2 3 import org.springframework.web.filter.CharacterEncodingFilter; 4 import org.springframework.web.servlet.DispatcherServlet; 5 import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 6 7 import javax.servlet.Filter; 8 import javax.servlet.ServletContext; 9 import javax.servlet.ServletException; 11 11 /** 12 * Initializes servlet WebApplicationContext 13 * 14 * @author chence. nie 15 * @date 2017/12/28 16 **/ 17 public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 18 19 @Override 20 protected Class<? >[] getRootConfigClasses() { 21 return new Class[]{AppConfig.class}; 22 } 23 24 @Override 25 protected Class<? >[] getServletConfigClasses() { 26 return new Class[]{DispatcherServlet.class}; 27 } 28 29 @Override 30 protected String[] getServletMappings() { 31 return new String[]{"/"}; 37 */ @override 41 protected Filter[] getServletFilters() {42} 37 */ @override 41 protected Filter[] getServletFilters() {42 CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); 43 characterEncodingFilter.setEncoding("UTF-8"); 44 characterEncodingFilter.setForceEncoding(true); 45 return new Filter[]{characterEncodingFilter}; 47 46}}Copy the code
This code has the same meaning as configuring SpringMVC:
1 <web-app>
2 <context-param>
3 <param-name>contextConfigLocation</param-name>
4 <param-value>/WEB-INF/root-context.xml</param-value>
5 </context-param>
6 <servlet>
7 <servlet-name>dispatcher</servlet-name>
8 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
9 <init-param>
10 <param-name>contextConfigLocation</param-name>
11 <param-value></param-value>
12 </init-param>
13 <load-on-startup>1</load-on-startup>
14 </servlet>
15 <servlet-mapping>
16 <servlet-name>dispatcher</servlet-name>
17 <url-pattern>/</url-pattern>
18 </servlet-mapping>
19 <listener>
20 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
21 </listener>
22 </web-app>Copy the code
5. application.properties
# database connection spring. The datasource. User = root spring. The datasource. The password = root spring. The datasource. The driver = com. Mysql.. JDBC driver spring.datasource.url=jdbc:mysql://localhost:3306/MySchool? CharacterEncoding = UTF-8 &useSSL=false #web setting related to spring.web.view.prefix=/ web-INF/JSP/spring.web.view.suffix=.jsp spring.web.static.handler=/assets/** spring.web.static.resource=classpath:/assets/ spring.web.static.cache.period=360000 # set mybatis related mybatis. Type. Alias. Package = com. BDQN. Lyrk. SSM. Study. The entityCopy the code
6. Create a mapper for MyBatis
package com.bdqn.lyrk.ssm.study.mapper;
import com.bdqn.lyrk.ssm.study.entity.StudentEntity;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface StudentMapper {
@Select("select * from Student")
List<StudentEntity> selectAll();
}Copy the code
7. Create service logic
1 package com.bdqn.lyrk.ssm.study.service.impl; 2 3 import com.bdqn.lyrk.ssm.study.entity.StudentEntity; 4 import com.bdqn.lyrk.ssm.study.mapper.StudentMapper; 5 import com.bdqn.lyrk.ssm.study.service.IStudentService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 import org.springframework.transaction.annotation.Transactional; 9 10 import java.util.List; 11 12 @Service 13 public class StudentServiceImpl implements IStudentService { 14 @Autowired 15 private StudentMapper studentMapper; 16 17 18 @Override 19 public List<StudentEntity> selectAll() { 20 return studentMapper.selectAll(); 21 } 22 23 @Transactional 24 @Override 25 public int save(StudentEntity studentEntity) { 26 return 0; 27} 28 29 30}Copy the code
8. To create the Controller
package com.bdqn.lyrk.ssm.study.controller; import com.bdqn.lyrk.ssm.study.entity.StudentEntity; import com.bdqn.lyrk.ssm.study.service.IStudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import java.util.List; @Controller public class IndexController { @Autowired private IStudentService studentService; @GetMapping("/index") public String index(ModelMap modelMap) { List<StudentEntity> list = studentService.selectAll(); modelMap.put("students", list); return "index"; }}Copy the code
9. Contents of the index.jsp file
<%-- Created by IntelliJ IDEA. User: chen.nie Date: 2017/12/23 Time: As in the afternoon To change this template use File | Settings | File Templates. - % > < % @ page contentType = "text/HTML. charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>$Title$</title> </head> <body> <c:forEach items="${students}" var="student"> ${student.stuName} </c:forEach> </body> </html>Copy the code
Visit http://localhost:8080/portal/index to get the following after 10. Start tomcat interface
OK! Finished, pay attention to the use of annotations in the first 4 steps, and the steps behind the usual writing method is the same, we must be very familiar with it.