SSM框架整合配置初始模板
使用idea工具,并使用了maven父工程模板(集中定义管理依赖版本)
打开父工程文件
新建module
开始整合配置
使用的依赖版本号
<!-- 集中定义依赖版本号 -->
<properties>
<junit.version>4.12</junit.version>
<spring.version>5.0.7.RELEASE</spring.version>
<mybatis.version>3.4.6</mybatis.version>
<mybatis.spring.version>1.3.2</mybatis.spring.version>
<mybatis.paginator.version>1.2.15</mybatis.paginator.version>
<mysql.version>5.1.32</mysql.version>
<slf4j.version>1.6.4</slf4j.version>
<jackson.version>2.9.0</jackson.version>
<fileupload.version>1.3.1</fileupload.version>
<druid.version>1.0.9</druid.version>
<httpclient.version>4.3.5</httpclient.version>
<jstl.version>1.2</jstl.version>
<servlet-api.version>2.5</servlet-api.version>
<jsp-api.version>2.0</jsp-api.version>
<joda-time.version>2.5</joda-time.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<commons-io.version>1.3.2</commons-io.version>
</properties>
第一步、spring和springMVC整合
1.1、引入module所需依赖和插件
<dependencies>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<!-- spring整合mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- Jackson Json处理工具包 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
注意:在子模块pom文件中添加打包方式,以及补全web项目目录结构。
1.2、配置spring
首先配置jdbc和log4j配置文件,放在resource里面,并新建一个专门存放 spring配置文件的文件夹,新建spring核心配置文件
1.2.1配置spring核心配置文件
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启注解扫描,在这里只扫描service包,controller交给springMVC扫描,mapper包使用mybatis不用扫描注解 -->
<context:component-scanbase-package="com.lee.service"/>
<!--引入jdbc配置文件-->
<context:property-placeholderlocation="classpath:jdbc.properties"/>
<!--jdbc参数-->
<beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource">
<propertyname="driverClassName"value="${jdbc.driverClassName}"/>
<propertyname="url"value="${jdbc.url}"/>
<propertyname="username"value="${jdbc.username}"/>
<propertyname="password"value="${jdbc.password}"/>
</bean>
</beans>
1.2.2在web.xml文件中配置spring核心监听器
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--配置spring核心监听器,在项目加载时就创建spring IOC容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
1.2.3创建IOC容器需要spring配置文件,加载spring配置文件
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--加载spring配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/applicationContext*.xml</param-value>
</context-param>
<!--配置spring核心监听器,在项目加载时就创建spring IOC容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
1.3、配置SpringMVC
1.3.1在web.xml文件中指定springMVC入口
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--加载spring配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/applicationContext*.xml</param-value>
</context-param>
<!--配置spring核心监听器,在项目加载时就创建spring IOC容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置springMVC入口-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置springMVC文件路径-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/springMVC-servlet.xml</param-value>
</init-param>
<!--配置实例化时机,默认第一次请求时实例化,设为0或正数则为项目时加载时并实例化-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<!--匹配拦截所有请求,除了jsp-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
1.3.2配置springMVC配置文件
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启注解扫描-->
<context:component-scanbase-package="com.lee.controller"/>
<!--注解驱动-->
<mvc:annotation-driven/>
<!--解决静态资源(html,js,css)被拦截-->
<mvc:default-servlet-handler/>
<!--配置视图解析器-->
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="prefix"value="/WEB-INF/jsp/"/>
<propertyname="suffix"value=".jsp"/>
</bean>
</beans>
1.4、测试spring和springMVC
1.4.1在WEB-INF/jsp文件下创建一个test.jsp文件
<%--
CreatedbyIntelliJIDEA.
User:LxY
Date:2018/11/19
Time:12:07
TochangethistemplateuseFile|Settings|FileTemplates.
--%>
<%@pagecontentType="text/html;charset=UTF-8"language="java"%>
<html>
<head>
<title>Title</title>
</head>
<body>
测试spring和SpringMVC
</body>
</html>
1.4.2在controller包下创建TestController
packagecom.lee.controller;
@Controller
@RequestMapping("test")
publicclassTestController{
@RequestMapping("ss")
publicStringtest(){
return"test";
}
}
运行结果:
1.5、配置mybatis
1.5.1spring-mybatis配置文件
在配置文件spring包中创建applicationContext-mybatis.xml配置文件,配置spring管理mybatis的配置
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--把SQLSession交给spring管理-->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据源-->
<propertyname="dataSource"ref="dataSource"/>
<!--注入mybatis配置文件-->
<propertyname="configLocation"value="classpath:mybatis/mybatis-config.xml"/>
<!--注入映射文件路径-->
<propertyname="mapperLocations"value="classpath:mybatis/mapper/**/*.xml"/>
<!--别名管理-->
<propertyname="typeAliasesPackage"value="com.lee.domain"/>
</bean>
<!--把mapper接口交给spring管理-->
<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
<propertyname="basePackage"value="com.lee.mapper"/>
</bean>
</beans>
1.5.2mybatis.xml文件配置
只需要配置一个驼峰匹配即可
<?xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--开启驼峰匹配-->
<settingname="mapUnderscoreToCamelCase"value="true"/>
</settings>
</configuration>
1.6、测试mybatis配置
1.6.1数据库准备
准备一张简单用户表
1.6.2编写对应实体类
packagecom.lee.domain;
publicclassUserimplementsSerializable{
privatestaticfinallongserialVersionUID=1L;
privateLongid;
// 用户名
privateStringuserName;
// 密码
privateStringpassword;
// 姓名
privateStringname;
// 年龄
privateIntegerage;
// 性别,1男性,2女性
privateIntegersex;
// 出生日期
privateDatebirthday;
// 创建时间
privateDatecreated;
// 更新时间
privateDateupdated;
publicLonggetId() {
returnid;
}
publicvoidsetId(Longid) {
this.id=id;
}
publicStringgetUserName() {
returnuserName;
}
publicvoidsetUserName(StringuserName) {
this.userName=userName;
}
publicStringgetPassword() {
returnpassword;
}
publicvoidsetPassword(Stringpassword) {
this.password=password;
}
publicStringgetName() {
returnname;
}
publicvoidsetName(Stringname) {
this.name=name;
}
publicIntegergetAge() {
returnage;
}
publicvoidsetAge(Integerage) {
this.age=age;
}
publicIntegergetSex() {
returnsex;
}
publicvoidsetSex(Integersex) {
this.sex=sex;
}
publicDategetBirthday() {
returnbirthday;
}
publicvoidsetBirthday(Datebirthday) {
this.birthday=birthday;
}
publicDategetCreated() {
returncreated;
}
publicvoidsetCreated(Datecreated) {
this.created=created;
}
publicDategetUpdated() {
returnupdated;
}
publicvoidsetUpdated(Dateupdated) {
this.updated=updated;
}
@Override
publicStringtoString() {
return"User [id="+id+", userName="+userName+", password="+password+", name="+name
+", age="+age+", sex="+sex+", birthday="+birthday+", created="+created
+", updated="+updated+"]";
}
}
1.6.3编写UserMapper接口
packagecom.lee.mapper;
publicinterfaceUserMapper{
/**
* 查找所有用户信息
* @return
*/
List<User>findAllUser();
}
1.6.4编写userMapper.xml文件
<?xmlversion="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mappernamespace="com.lee.mapper.UserMapper">
<!--查找所有用户信息-->
<selectid="findAllUser"resultType="User">
select * from tb_user
</select>
</mapper>
1.6.5编写对应的测试单元
packagecom.lee.test;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/applicationContext*.xml")
publicclassUserTest{
@Autowired
privateUserMapperuserMapper;
@Test
publicvoidtest1() {
List<User>list=userMapper.findAllUser();
for(Useruser:list) {
System.out.println(user);
}
}
}
遇到问题:
第一次报错内容如下:
java.lang.IllegalStateException:FailedtoloadApplicationContext
atorg.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
atorg.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
atorg.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
atorg.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
atorg.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
atorg.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
atorg.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
atorg.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
atorg.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
atorg.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
atorg.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
atorg.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
atorg.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
atorg.junit.runners.ParentRunner.run(ParentRunner.java:363)
atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
atorg.junit.runner.JUnitCore.run(JUnitCore.java:137)
atcom.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
atcom.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
atcom.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
atcom.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Causedby:org.springframework.beans.factory.BeanCreationException:Errorcreatingbeanwithname'sqlSessionFactory'definedinfile[E:\java\04-SSM\parent\springSSM\target\classes\spring\applicationContext-mybatis.xml]:Initializationofbeanfailed;nestedexceptionisorg.springframework.beans.TypeMismatchException:Failedtoconvertpropertyvalueoftype'java.lang.String'torequiredtype'java.lang.Class[]'forproperty'typeAliases';nestedexceptionisjava.lang.IllegalArgumentException:Couldnotfindclass[com.lee.domain]
atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:589)
atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503)
atorg.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
atorg.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
atorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
atorg.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
atorg.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:741)
atorg.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
atorg.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
atorg.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
atorg.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
atorg.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:107)
atorg.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:243)
atorg.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
atorg.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
...24more
Causedby:org.springframework.beans.TypeMismatchException:Failedtoconvertpropertyvalueoftype'java.lang.String'torequiredtype'java.lang.Class[]'forproperty'typeAliases';nestedexceptionisjava.lang.IllegalArgumentException:Couldnotfindclass[com.lee.domain]
atorg.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:595)
atorg.springframework.beans.AbstractNestablePropertyAccessor.convertForProperty(AbstractNestablePropertyAccessor.java:604)
atorg.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:219)
atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1660)
atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1616)
atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1363)
atorg.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:580)
...38more
Causedby:java.lang.IllegalArgumentException:Couldnotfindclass[com.lee.domain]
atorg.springframework.util.ClassUtils.resolveClassName(ClassUtils.java:313)
atorg.springframework.beans.propertyeditors.ClassArrayEditor.setAsText(ClassArrayEditor.java:70)
atorg.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:466)
atorg.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:439)
atorg.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:192)
atorg.springframework.beans.AbstractNestablePropertyAccessor.convertIfNecessary(AbstractNestablePropertyAccessor.java:585)
...44more
Causedby:java.lang.ClassNotFoundException:com.lee.domain
atjava.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
atjava.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
atjava.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
atorg.springframework.util.ClassUtils.forName(ClassUtils.java:274)
atorg.springframework.util.ClassUtils.resolveClassName(ClassUtils.java:310)
...49more
原因:
applicationContext-mybatis.xml 配置文件中配置错误,
<!--别名管理-->
<propertyname="typeAliases"value="com.lee.domain"/>
修改为:
<!--别名管理-->
<propertyname="typeAliasesPackage"value="com.lee.domain"/>
运行正确后测试结果:
1.7、配置事务
1.7.1在spring中配置事务
在资源包spring下创建applicationContext-tx.xml事务配置文件
<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置事务管理器-->
<beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--其中ref可能会报红,应该是软件问题,把项目关了再开就解决-->
<propertyname="dataSource"ref="dataSource"/>
</bean>
<!--配置事务属性-->
<tx:adviceid="txAdvice"transaction-manager="transactionManager">
<tx:attributes>
<!--配置查询数据库的方法中find开头的只读-->
<tx:methodname="find*"read-only="true"/>
<!--配置其他方法可读写(默认)-->
<tx:methodname="*"/>
</tx:attributes>
</tx:advice>
<!--配置事务切面-->
<aop:config>
<aop:pointcutid="pointcut"expression="execution(* com.lee.service.impl.*.*(..))"/>
</aop:config>
</beans>
1.8、总结
至此SSM框架简单配置已经完整。
1.9、附上整体项目目录结构
网友评论