SSM JavaConfig方式配置(推荐)
资料:https://my.oschina.net/u/3429289/blog/1649294
作为记录放在这里,网上这类的配置文件不是很多 在这里放一个供大家参考
好处是弄完了不需要xml配置文件,只需要一些经常改动的变成配置文件即可
不用xml文件后不再有一些奇怪的小叹号、红叉、命名空间文件了
Servlet3.0 开始就不需要web.xml配置文件进行配置了,所有的servlet、filter、listener等都是用注解配置
1、 pom文件
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>SSMJavaConfig</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SSMJavaConfig MavenWebapp</name>
<url>http://maven.apache.org</url>
<!-- 版本 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.12</junit.version>
<spring.version>4.3.0.RELEASE</spring.version>
<jackson.version>2.5.0</jackson.version>
<mysql-connector-java.version>5.1.37</mysql-connector-java.version>
<fastjson.version>1.2.3</fastjson.version>
<slf4j.version>1.7.12</slf4j.version>
<commons-io.version>2.4</commons-io.version>
<commons-fileupload.version>1.3.2</commons-fileupload.version>
<commons-collections.version>3.2.2</commons-collections.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<commons-codec.version>1.10</commons-codec.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<druid.version>1.0.16</druid.version>
<mybatis.version>3.4.0</mybatis.version>
<mybatis-spring.version>1.3.0</mybatis-spring.version>
<mybatis-plugin.version>5.1.3</mybatis-plugin.version>
</properties>
<!-- 依赖管理 -->
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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-web</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-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- jdbc驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<!--common 组件 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commons-collections.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<!-- 日志处理 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- servlet -->
<!-- javax.servlet相关 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- 分页插件pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>${mybatis-plugin.version}</version>
</dependency>
</dependencies>
<build>
<finalName>SSMJavaConfig</finalName>
</build>
</project>
2、 配置Spring MVC
2.1、初始化
首先创建一个初始化类,继承AbstractAnnotationConfigDispatcherServletInitializer类,这里继承AbstractAnnotationConfigDispatcherServletInitializer类,就会自动个地配置Dispatcher-Servlet和Spring上下文(传统的方法是在web.xml中配置 DispatcherServlet)
RootConfig、WebConfig、这两个配置类现在还没有,下面会创建
package com.conf;
importorg.apache.log4j.Logger;
importorg.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
publicclassWebAppInitializer extendsAbstractAnnotationConfigDispatcherServletInitializer {
privatefinalstatic Logger LOG = Logger.getLogger(WebAppInitializer.class);
@Override
protectedClass<?>[] getRootConfigClasses() {
LOG.info("------root配置类初始化------");
returnnewClass<?>[] { RootConfig.class };
}
@Override
protectedClass<?>[] getServletConfigClasses() {
LOG.info("------web配置类初始化------");
returnnewClass<?>[] { WebConfig.class };
}
@Override
protected String[]getServletMappings() {
LOG.info("------映射根路径初始化------");
returnnew String[] { "/" };// 请求路径映射,将路径映射到DispatcherServlet上,这里可以配置成/* 拦截所有
}
}
2.2 剖析 AbstractAnnotationConfigDispatcherServletInitializer
Servlet3.0环境中,容器会在类路径去查找实现javax.servlet.ServletContainerInitializer接口的类,如果发现,就用它做servlet的容器
Spring对这个接口进行了实现,为SpringServletContainerInitializer。它( SpringServletContainerInitializer )会去查找实现了WebAppInitializer的类并将配置任务交给他们来完成。Spring3.2引入了便利的 WebAppInitializer 实现,就是AbstractAnnotationConfigDispatcherServletInitializer。所以当部署到Servlet3.0容器中时,容器会自动发现它,并配置servlet上下文
重新的三个方法也有对应注解,这里不再多说
2.3、WebConfig配置
当DispatcherServlet启动的时候,会创建Spring应用上下文并加载配置文件或配置文件中声明的bean。
该配置类相当于之前的spring-mvc.Xml 文件
当它加载上下文时,使用定义在WebConfig中的bean(基于java配置)
DispatcherServlet 加载包含web组件的bean,如控制器,视图解析器等。还有一个ContextLoaderListener加载其他bean,如中间层及数据层组件等
@Configuration:配置类
@EnableWebMvc:相当于基于xml配置的<mvc:annotation-driven>启用注解驱动
@ComponentScan:包扫描
package com.conf;
importorg.springframework.beans.factory.annotation.Configurable;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.ComponentScan;
importorg.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
importorg.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
importorg.springframework.web.servlet.config.annotation.EnableWebMvc;
importorg.springframework.web.servlet.view.InternalResourceViewResolver;
/**
* 定义 DispatcherServlet 加载应用上下文的配置
* 该配置类相当于之前的spring-mvc.Xml 文件
* @author 80511
*
*/
@Configurable
@EnableWebMvc
@ComponentScan("com.controller") // 包扫描
publicclass WebConfig extendsWebMvcConfigurerAdapter {
@Bean
publicViewResolver viewResolver() {
InternalResourceViewResolverresolver = newInternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp");
resolver.setSuffix(".jsp");
returnresolver;
}
@Bean(name = "multipartResolver") // bean必须写name属性且必须为multipartResolver
protectedCommonsMultipartResolver multipartResolver(){
CommonsMultipartResolvercommonsMultipartResolver = newCommonsMultipartResolver();
commonsMultipartResolver.setMaxUploadSize(5* 1024 * 1024);
commonsMultipartResolver.setMaxInMemorySize(0);
commonsMultipartResolver.setDefaultEncoding("UTF-8");
returncommonsMultipartResolver;
}
// 默认实现的静态资源的处理
/* @Override
publicvoid configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
System.out.println("*******************************************************");
configurer.enable();
}*/
// 自定义实现过滤那些文件
@Override
publicvoidaddResourceHandlers(ResourceHandlerRegistry registry) {
//等价于 <mvc:resources mapping="/imgs/**"location="/imgs/"/>
registry.addResourceHandler("/imgs/**").addResourceLocations("/imgs/");
}}
3、 RootConfig配置
这里数据库的事务配置方式有三种:
第一种在RootConfig加上 @EnableTransactionManagement 注解,配置数据库, 手动加上事务使用@Transactional 注解,并且指定的传播属性,缺点麻烦
第二种使用BeanNameAutoProxyCreator拦截代理方式(这里使用的是这种方式)
第三种是采用aop切面事务
DataSourceConfig类这里还没有,下面会创建
package com.conf;
importorg.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.ComponentScan;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.Import;
/**
* 主要配置持久层的一些东西,包括数据库、Mybatis框架,事务之类的
* @author 80511
*
*/
@Configuration
@ComponentScan(basePackages = {"com.config", "com.service" })
@Import(DataSourceConfig.class)
publicclass RootConfig{
@Bean
publicBeanNameAutoProxyCreator autoProxyCreator() {
BeanNameAutoProxyCreatorautoProxyCreator = newBeanNameAutoProxyCreator();
autoProxyCreator.setProxyTargetClass(true);
// 设置要创建代理的那些Bean的名字,符合该名称的service类都会被加上事务
autoProxyCreator.setBeanNames("*Service");
autoProxyCreator.setInterceptorNames("transactionInterceptor");
returnautoProxyCreator;
}
}
4、 DataSourceConfig(dao、mapper)
打开@PropertySources注解扫描配置文件,然后注入到属性中,还有很多其他连接池配置仿照添加即可
package com.conf;
importjava.io.IOException;
importjava.util.Properties;
importjavax.sql.DataSource;
importorg.apache.log4j.Logger;
importorg.mybatis.spring.SqlSessionFactoryBean;
importorg.mybatis.spring.annotation.MapperScan;
importorg.springframework.beans.factory.annotation.Configurable;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.PropertySource;
importorg.springframework.context.annotation.PropertySources;
importorg.springframework.context.support.PropertySourcesPlaceholderConfigurer;
importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
importorg.springframework.jdbc.datasource.DataSourceTransactionManager;
importorg.springframework.transaction.interceptor.TransactionInterceptor;
importcom.alibaba.druid.pool.DruidDataSource;
@Configurable
@PropertySources(value = { @PropertySource("classpath:/jdbc.properties") })
@MapperScan("com.mapper")//扫描mapper
publicclassDataSourceConfig {
privatefinalstatic Logger LOG = Logger.getLogger(DataSourceConfig.class);
@Value("${spring.datasource.driver}")
private String driver;
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
/*
* 这个bean必须配置而且必须是静态方法,如果不配置就不能进行@Value的属性注入
*/
@Bean
publicstaticPropertySourcesPlaceholderConfigurer placeholderConfigurer() {
returnnewPropertySourcesPlaceholderConfigurer();
}
@Bean
public DataSourcedataSource() {
LOG.info("Initializethe BasicDataSource...");
DruidDataSourcedatasource = newDruidDataSource();
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driver);
//configuration 以后需要自己加
/* datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
LOG.error("druid configuration initialization filter",e);
}
datasource.setConnectionProperties(connectionProperties); */
returndatasource;
}
// mybatis的配置
@Bean
publicSqlSessionFactoryBean sqlSessionFactoryBean() throws IOException{
ResourcePatternResolverresourcePatternResolver = newPathMatchingResourcePatternResolver();
SqlSessionFactoryBeansqlSessionFactoryBean = newSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath:/com/mapper/*.xml"));
// 别名,让*Mpper.xml实体类映射可以不加上具体包名,会从spring中找到mapper类(就是之前的dao接口)
sqlSessionFactoryBean.setTypeAliasesPackage("com.mapper");
//mybatis配置文件
sqlSessionFactoryBean.setConfigLocation(resourcePatternResolver.getResource("classpath:/mybatis-config.xml"));
returnsqlSessionFactoryBean;
}
// 事务管理器对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
@Bean(name = "transactionManager")
publicDataSourceTransactionManager dataSourceTransactionManager() {
DataSourceTransactionManagerdataSourceTransactionManager = newDataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource());
returndataSourceTransactionManager;
}
/*
* 配置事务级别,这里是根据方法名配置的
*/
@Bean(name = "transactionInterceptor")
publicTransactionInterceptor interceptor() {
TransactionInterceptorinterceptor = newTransactionInterceptor();
interceptor.setTransactionManager(dataSourceTransactionManager());
PropertiestransactionAttributes = newProperties();
transactionAttributes.setProperty("save*", "PROPAGATION_REQUIRED");
transactionAttributes.setProperty("del*", "PROPAGATION_REQUIRED");
transactionAttributes.setProperty("update*", "PROPAGATION_REQUIRED");
transactionAttributes.setProperty("get*", "PROPAGATION_REQUIRED,readOnly");
transactionAttributes.setProperty("find*", "PROPAGATION_REQUIRED,readOnly");
transactionAttributes.setProperty("*", "PROPAGATION_REQUIRED");
interceptor.setTransactionAttributes(transactionAttributes);
returninterceptor;
}
}
5、 mybatis-config配置文件
用这个主要是为了使用分页插件pagehelper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--打印查询语句 NO_LOGGING | STDOUT_LOGGING-->
<settings>
<setting name="logImpl" value="NO_LOGGING"/>
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 5.0版本可以自动识别不需要写,写上就错了
<property name="dialect"value="mysql" /> -->
<!-- 该参数默认为false -->
<!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
<!-- 和startPage中的pageNum效果一样 -->
<property name="offsetAsPageNum" value="true" />
<!-- 该参数默认为false -->
<!-- 设置为true时,使用RowBounds分页会进行count查询 -->
<property name="rowBoundsWithCount" value="true" />
<!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
<!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型) -->
<property name="pageSizeZero" value="true" />
<!--3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
<!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
<!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
<property name="reasonable" value="false" />
<!--3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
<!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
<!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值 -->
<!-- 不理解该含义的前提下,不要随便复制该配置 -->
<!--<property name="params" value="pageNum=start;pageSize=limit;"/>-->
</plugin>
</plugins>
</configuration>