搭建各个模块的测试环境
整合说明:我们通常使用Spring框架来整合SpringMVC和Mybatis,且使用注解+XML的形式
整合的思路
先搭建整合的环境(porm.xml)
先把Spring的配置搭建完成
再使用Spring整合SpringMVC框架
最后使用Spring整合MyBatis框架
整合的porm.xml
<dependencies> <dependency> <groupId>org.aspectjgroupId> <artifactId>aspectjweaverartifactId> <version>1.6.8version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-aopartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.12version> <scope>testscope> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>${mysql.version}version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>servlet-apiartifactId> <version>2.5version> <scope>providedscope> dependency> <dependency> <groupId>javax.servlet.jspgroupId> <artifactId>jsp-apiartifactId> <version>2.0version> <scope>providedscope> dependency> <dependency> <groupId>jstlgroupId> <artifactId>jstlartifactId> <version>1.2version> dependency> <dependency> <groupId>log4jgroupId> <artifactId>log4jartifactId> <version>${log4j.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-apiartifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>org.slf4jgroupId> <artifactId>slf4j-log4j12artifactId> <version>${slf4j.version}version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>${mybatis.version}version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatis-springartifactId> <version>1.3.0version> dependency> <dependency> <groupId>c3p0groupId> <artifactId>c3p0artifactId> <version>0.9.1.2version> <type>jartype> <scope>compilescope> dependency>dependencies>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="service">context:component-scan> <context:component-scan base-package="dao">context:component-scan>beans>
public class TestSpring { private AccountService accountService; @Before public void init(){ ApplicationContext ac=new ClassPathXmlApplicationContext("ApplicationContext.xml"); accountService = ac.getBean("accountService", AccountService.class); } @Test public void testSpring(){ accountService.findAll(); }}
<filter> <filter-name>encodingfilter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class> <init-param> <param-name>encodingparam-name> <param-value>UTF-8param-value> init-param>filter><filter-mapping> <filter-name>encodingfilter-name> <url-pattern>/*url-pattern>filter-mapping><servlet> <servlet-name>dispatcherServletservlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:SpringMVC.xmlparam-value> init-param> <load-on-startup>1load-on-startup>servlet><servlet-mapping> <servlet-name>dispatcherServletservlet-name> <url-pattern>/url-pattern>servlet-mapping>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="controller">context:component-scan> <mvc:annotation-driven>mvc:annotation-driven> <bean id="viewController" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="pages/">property> <property name="suffix" value=".jsp">property> bean> <mvc:resources mapping="/js/**" location="/js/">mvc:resources> <mvc:resources mapping="/css/**" location="/css/">mvc:resources> <mvc:resources mapping="/images/**" location="/images/">mvc:resources>beans>
@Controllerpublic class AccountController { @RequestMapping("testMVC") public String testMVC(){ System.out.println("testMVC执行了!"); return "success"; }}
configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC">transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm"/> <property name="username" value="root"/> <property name="password" value="123456"/> dataSource> environment> environments> <mappers> <package name="dao"/> mappers>configuration>
public interface AccountDao { //查询所有 @Select("select * from account") public List findAll(); //保存 @Insert("insert into account (name,money) values(#{name},#{money}) ") public void saveAccount(Account account);}
public class TestMybatis { AccountDao proxyAccount; SqlSession session; InputStream in; @Before public void init() throws Exception { //加载配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //创建SqlSessionFactory工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //根据工厂创建SqlSession对象 session = factory.openSession(); //创建代理对象 proxyAccount = session.getMapper(AccountDao.class); } @After public void destroy() throws IOException { //提交事务 session.commit(); session.close(); in.close(); } @Test public void testMybatis() { Account account=new Account(); account.setName("lisi"); account.setMoney(200d); //测试保存 proxyAccount.saveAccount(account); }}
实现步骤
在项目启动的时候,就去加载applicationContext.xml的配置文件,创建好容器
在web.xml中配置ContextLoaderListener监听器(该监听器默认只能加载WEB-INF目录下的applicationContext.xml的配置文件)
更多java资料点击此处领取
在controller中注入service对象,调用service对象的方法进行测试
<listener> <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>listener><context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:ApplicationContext.xmlparam-value>context-param>
@Controllerpublic class AccountController { @Autowired private AccountService accountService; @RequestMapping("testMVC") public String testMVC(){ System.out.println("表现层:testMVC执行了!"); accountService.findAll(); return "success"; }}
<bean id="DataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver">property> <property name="url" value="jdbc:mysql://localhost:3306/ssm">property> <property name="username" value="root">property> <property name="password" value="123456">property>bean><bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="DataSource">property>bean><bean id="mappers" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="dao">property>bean>
@Repositorypublic interface AccountDao { //查询所有 @Select("select * from account") public List findAll(); //保存 @Insert("insert into account (name,money) values(#{name},#{money}) ") public void saveAccount(Account account);}
@Service("accountService")public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override public List findAll() { System.out.println("业务层:findAll方法执行了..."); List lists = accountDao.findAll(); return lists; }}
@Controllerpublic class AccountController { @Autowired private AccountService accountService; @RequestMapping("testMVC") public String testMVC(ModelMap model){ System.out.println("表现层:testMVC执行了!"); List accounts = accountService.findAll(); model.addAttribute("accounts",accounts); return "success"; }}
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="DataSource">property> bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="find*" read-only="true" propagation="SUPPORTS"/> <tx:method name="*" propagation="REQUIRED">tx:method> tx:attributes> tx:advice> <aop:config> <aop:pointcut id="pt1" expression="execution(* service.impl.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1">aop:advisor> aop:config>
@RequestMapping("testSave")public void testSave(Account account,HttpServletRequest req, HttpServletResponse resp) throws IOException { System.out.println("表现层:testSave执行了!"); accountService.saveAccount(account); resp.sendRedirect(req.getContextPath()+"/testFindAll"); return;}