Spring
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 J2EE 应用程序开发提供集成的框架。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。Spring的核心是控制反转(IoC)和面向切面(AOP)。
Spring优点
1.降低了组件之间的耦合性 ,实现了软件各层之间的解耦
2.可以使用容易提供的众多服务,如事务管理,消息服务等
3.容器提供单例模式支持
4.容器提供了AOP技术,利用它很容易实现如权限拦截,运行期监控等功能
5.容器提供了众多的辅助类,能加快应用的开发
6.spring对于主流的应用框架提供了集成支持,如hibernate,JPA,Struts等
7.spring属于低侵入式设计,代码的污染极低
8.独立于各种应用服务器
9.spring的DI机制降低了业务对象替换的复杂性
10.Spring的高度开放性,并不强制应用完全依赖于Spring,开发者可以自由选择spring的部分或全部
Spring IOC
IOC是inverse of control的简写,译为控制反转,是一种创建对象的思想。
控制反转 就是将创建对象的权力交给Spring容器,其实就是让Spring容器帮你创建对象,而你不需要在javel代码中new对象了。用来降低程序代码之间的耦合程度,也称为依赖注入,是面向对象一种设置理念。
Spring IOC所需架包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
SpingIOC容器
容器所为SpringIOC的核心它主要有两种:
-
BeanFactory:BeanFactory为IOC容器提供了基础功能,Spring文档中提到,当前该类仅仅是为了向后兼容老的版本,除非你有更好的原因否则就应该使用第二种容器。
-
ApplicationContext:通过API文档可以知道,ApplicationContext是BeanFactory的子接口,并且从文档中也可以看到ApplicaionContext除了包含有BeanFactory的所有功能还支持了更多的功能。
ApplicationContext的实现有四种方式:
-
FileSystemXmlApplicationContext:加载配置文件的时候采用的是项目的路径。
-
ClassPathXmlApplicationContext:加载配置文件的时候根据ClassPath位置。
-
XmlWebApplicationContext:在Web环境下初始化监听器的时候会加载该类。
-
AnnotationConfigApplicationContext:根据注解的方式启动Spring 容器
实现IOC控制反转的条件:
- 想要获取对象的类或者接口和接口的实现类
- 创建对象的Spring容器
- 用来获取容器中指定对象的类的对象
- 用来使用从容器中获的对象的类。
创建Spring容器文件(即xxx.xml)
在applicationContext.xml中引入dtd规则
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"https://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
</beans>
提供javabean,即创建InterfaceA接口和其实现类ClassA
//InterfaceA接口
package testspringIOCDI.ioc;
public interface InterfaceA {
public String getInfo();
public void method();
}
//创建InterfaceA的实现类ClassA
package testspringIOCDI.ioc;
public class ClassA implements InterfaceA {
public ClassA(){}
public String getInfo() {
// TODO Auto-generated method stub
return "企业管理系统模块:实现公告发布、修改、删除等操作";
}
public void method(){
System.out.println("I'm classA");
}
}
在Spring容器(applicationContext.xml.xml)中写创建ClassA类的对象classa的配置代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"https://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<description>applicationContext</description>
<bean id="classa" class="testspringIOCDI.ioc.ClassA"></bean>
<!-- id 唯一标识,class 提供类,必须包含无参构造,相当于 ClassA classa=new ClassA(); -->
</beans>
获取javabean(即classa对象)并使用
package testspringIOCDI.ioc;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class IOCTest {
/**
* Test method for {@link testspringIOCDI.ioc.ClassA#getInfo()}.
*/
@Test
public void testGetInfo() {
//通过(加载)xml容器获取上下文实例//通过规则指定xml文件
ApplicationContext context=new FileSystemXmlApplicationContext("/src/main/resources/SpringIOC.xml");
//方式一:根据xml中配置的ID获取的对象(ID唯一),返回Object需要强转类型
InterfaceA ia=(InterfaceA) context.getBean("classa");
System.out.println("方式一"+ia.getInfo());
//方式二:根据ID,指定接口类型的类型获取对象(不需要强转类型)
InterfaceA ia2=context.getBean("classa",InterfaceA.class);
System.out.println("方式二:"+ia2.getInfo());
//方式三:根据接口类型获取对象(xml配置只有一个实现类的情况下)
InterfaceA ia3=context.getBean(InterfaceA.class);
System.out.println("方式三:"+ia3.getInfo());
context=null;//释放处理
}
}
Spring AOP
面向切面编程,能够让我们在不影响原有功能的前提下,为软件横向扩展功能 。AOP解决了OOP中遇到的一些问题,是OOP的延续和扩展。
Spring AOP所需架包
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
Spring AOP概念
1.通知(Advice)
就是你想要的功能,也就是上面说的 安全,事物,日志等。你给先定义好把,然后在想用的地方用一下。
2.连接点(JoinPoint)
这个更好解释了,就是spring允许你使用通知的地方,那可真就多了,基本每个方法的前,后(两者都有也行),或抛出异常时都可以是连接点,spring只支持方法连接点.其他如aspectJ还可以让你在构造器或属性注入时都行,不过那不是咱关注的,只要记住,和方法有关的前前后后(抛出异常),都是连接点。
3.切入点(Pointcut)
上面说的连接点的基础上,来定义切入点,你的一个类里,有15个方法,那就有几十个连接点了对把,但是你并不想在所有方法附近都使用通知(使用叫织入,以后再说),你只想让其中的几个,在调用这几个方法之前,之后或者抛出异常时干点什么,那么就用切点来定义这几个方法,让切点来筛选连接点,选中那几个你想要的方法。
4.切面(Aspect)
切面是通知和切入点的结合。现在发现了吧,没连接点什么事情,连接点就是为了让你好理解切点,搞出来的,明白这个概念就行了。通知说明了干什么和什么时候干(什么时候通过方法名中的before,after,around等就能知道),而切入点说明了在哪干(指定到底是哪个方法),这就是一个完整的切面定义。
5.引入(introduction)
允许我们向现有的类添加新方法属性。这不就是把切面(也就是新方法属性:通知定义的)用到目标类中吗
6.目标(target)
引入中所提到的目标类,也就是要被通知的对象,也就是真正的业务逻辑,他可以在毫不知情的情况下,被咱们织入切面。而自己专注于业务本身的逻辑。
7.代理(proxy)
怎么实现整套aop机制的,都是通过代理,这个一会给细说。
8.织入(weaving)
基于注解的AOP配置方式
切面类:
package com.enjoy.cap10.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
//日志切面类
@Aspect
public class LogAspects {
public void pointCut(){};
//@before代表在目标方法执行前切入, 并指定在哪个方法前切入
@Before("pointCut()")
public void logStart(){
System.out.println("除法运行....参数列表是:{}");
}
@After("pointCut()")
public void logEnd(){
System.out.println("除法结束......");
}
@AfterReturning("pointCut()")
public void logReturn(){
System.out.println("除法正常返回......运行结果是:{}");
}
@AfterThrowing("pointCut()")
public void logException(){
System.out.println("运行异常......异常信息是:{}");
}
@Around("pointCut()")
public Object Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("@Arount:执行目标方法之前...");
Object obj = proceedingJoinPoint.proceed();//相当于开始调div地
System.out.println("@Arount:执行目标方法之后...");
return obj;
}
}
目标方法:
package com.enjoy.cap10.aop;
public class Calculator {
//业务逻辑方法
public int div(int i, int j){
System.out.println("--------");
return i/j;
}
}
配置类:
package com.enjoy.cap10.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.enjoy.cap10.aop.Calculator;
import com.enjoy.cap10.aop.LogAspects;
@Configuration
public class Cap10MainConfig {
@Bean
public Calculator calculator(){
return new Calculator();
}
@Bean
public LogAspects logAspects(){
return new LogAspects();
}
}
测试类:
public class Cap10Test {
@Test
public void test01(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Cap10MainConfig.class);
Calculator c = app.getBean(Calculator.class);
int result = c.div(4, 3);
System.out.println(result);
app.close();
}
}
IoC和AOP使用扩展
Spring的AOP配置
1、使用的是Aspectj第三方框架,实现了AOP思想
2、注解配置的AOP
3、纯POJO 就是一个普通的类aop:config
- UserBiz类给它一个方法:
1 package cn.happy.biz;
2
3 public class UserBiz {
4 public void addStu(UserInf user){
5 System.out.println("add ok");
6 }
7 }
- 在aop包下BeforeAdvice前置增强类,它需要实现MethodBeforeAdvice接口的before方法:
1 import org.springframework.aop.MethodBeforeAdvice;
2
3 /**
4 * before
5 *
6 */
7 public class BeforeAdvice implements MethodBeforeAdvice{
8
9 /**
10 *
11 * @param method 被代理的目标的方法
12 * @param args 传递给目标方法的参数
13 * @param obj 被代理的目标对象
14
15 * @throws Throwable
16 */
17 @Override
18 public void before(Method method, Object[] args , Object obj)
19 throws Throwable {
20 System.out.println("========before======");
21 }
- 配置文件(注意引入的命名空间)aop:config配置下实现切面:
1 ......
2 <bean id="biz" class="cn.happy.biz.UserBiz"></bean>
3
4 <!-- 前置 -->
5 <bean id="beforeAdvice" class="cn.happy.aop.BeforeAdvice"></bean>
6 <!-- aop配置切面 -->
7 <aop:config>
8 <!-- 定义切点 -->
9 <aop:pointcut expression="execution(public void *(cn.happy.biz.UserInf))" id="pointcut"/>
10 <!-- 增强处理和切点结合 -->
11 <aop:advisor advice-ref="beforeAdvice" pointcut-ref="pointcut"/>
12 <aop:advisor advice-ref="afterAdivice" pointcut-ref="pointcut"/>
13 </aop:config>
14 ......
- 测试类:
1 public void testOne(){
2 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
3 UserBiz biz = (UserBiz)ctx.getBean("biz");
4 biz.addStu(new UserInf());
5
6 }
- 定义一个接口:
在这里插入代码片1 public interface ISomeService {
2 //1.1 执行事务
3 public void doTransaction();
4 //1.2 书写日志
5 public String doLog();
6 }
- 实现接口的实现类:
1 public class SomeServiceImpl implements ISomeService {
2
3 public void doTransaction() {
4 System.out.println("开启事务");
5 }
6
7 public String doLog() {
8 System.out.println("书写日志"+5/0);
9 return "我是书写日志的返回值哦!!!!!";
10 }
11
12 }
- 增强类用注解写:
1 @Aspect
2 public class MyAspect {
3 //前置通知
4 @Before(value="execution(public * *(..))")
5 public void MyBefore(){
6 System.out.println("这是前置通知哦!!!!!!!在执行目标对象之前执行");
7 }
8
9 //后置通知
10 @AfterReturning(value="execution(public * *(..))")
11 public void MyAfterReturning(){
12 System.out.println("这是后置通知哦!!!!!!!在执行目标对象之前执行");
13 }
14
15 //环绕通知
16 /* @Around(value="execution(public * *(..))")
17 public void MyAround(ProceedingJoinPoint pjp){
18 System.out.println("这是环绕通知前哦!!!!!!!在执行目标对象之前执行");
19 try {
20 pjp.proceed();
21 System.out.println("这是环绕通知后哦!!!!!!!在执行目标对象之前执行");
22 } catch (Throwable e) {
23 // TODO Auto-generated catch block
24 e.printStackTrace();
25 }
26 }*/
27
28 //异常通知
29 @AfterThrowing(value="execution(public * *(..))")
30 public void MyAfterThrowing(){
31 System.out.println("这是异常通知哦!!!!!!!在执行目标对象之前执行");
32 }
33
34 //最终通知
35 @After(value="execution(public * *(..))")
36 public void MyAfter(){
37 System.out.println("这是最终通知哦!!!!!!!在执行目标对象之前执行");
38 }
39 }
- 配置文件:
1 <!-- 目标对象 -->
2 <bean id="someService" class="cn.happy.enetity.SomeServiceImpl"></bean>
3
4 <!-- 切面: -->
5 <bean id="myAspect" class="cn.happy.aspece.MyAspect"></bean>
6 <!--aop:aspectj可以启动对@AspectJ注解支持-->
7 <aop:aspectj-autoproxy/>
8 </beans>
- 测试类:
1 public void testOne(){
2
3 ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
4 ISomeService service = (ISomeService)ctx.getBean("someService");
5 service.doTransaction();
6 String result = service.doLog();
7 System.out.println(result);
8 }
Spring MVC
MVC设计模式
是一种架构模式,将业务逻辑和页面展示分离,使程序分层、分工合作,既相互独立,又协同合作。
M(Model)+V(View)+C(Controller)
-
M(模型层):业务数据的信息表示,通常是业务实体
-
V(视图层):为用户呈现数据的页面
-
C(控制层):调用业务逻辑产生合适的数据(Model),同时传递数(Model)给视图层(View)呈现给用户
分层设计
- 数据访问接口:DAO层
- 处理业务逻辑Service层
- 数据实体POJO
- 负责前段请求的接受并接受处理:Servlet
- 负责前段页面展示:JSP
MVC优点
-
完全基于接口编程,真正实现了视图无关。除了jsp,还可以使用Velocity和xstl或其他视图技术,甚至是自定义的视图技术–只需要简单的实现view接口
-
Spring MVC框架以DispatchServlet为核心控制器,该控制器负责拦截用户的所有请求
-
Spring MVC所有控制器都必须实现Controler接口,该接口定义了ModelAndView handleRequest(request,response)方法,通过实现该接口实现用户的业务逻辑控制。
MVC缺点
-
Spring与MVC 的Servlet API 耦合,难以脱离容器独立运行
-
太过于细分,开发效率低
-
过度追求完美,有过度设计的危险
Spring MVC环境搭配
<!-- https://mvnrepository.com/artifact/aopp;alliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
- 在web.xml中配置Servlet
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--初始化参数-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 创建SpringMVC的配置文件(springmvc-servlet.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/p
http://www.springframework.org/schema/p/spring-p.xsd">
<bean name="/index.html" class="smbms.controller.IndexController1"></bean>
<!--完成视图的对应-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 创建Controller
package smbms.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class IndexController1 extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
System.out.println("hello,SpringMvc!");
return new ModelAndView("index");
}
}
- 创建View
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>hello,SpringMVC!</h1>
</body>
</html>
Spring MVC 框架的特点
- 清晰地角色划分
- 灵活的配置功能
- 提供大量的控制器接口和实现类
- 真正做到与View层实现类无关
- 国际化支持
- 面向接口编程
- Spring提供了Web应用开发的一整套流程,可以方便的结合在一起
Mybatis与Spring的整合
导入jar包
创建两个Source Folder文件夹( resources和test)
创建dao层接口、实现类、mapper映射文件
1、Dao接口:
package com.bdqn.dao.user;
import java.util.List;
import com.bdqn.pojo.User;
public interface UserMapper {
/**
* 按照用户名和用户角色查找用户列表
* @param user
* @return
*/
List<User> getUsers(User user);
}
2、Dao的实现类:
package com.bdqn.dao.user;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import com.bdqn.pojo.User;
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSession;
@Override
public List<User> getUsers(User user) {
return sqlSession.selectList("com.bdqn.dao.user.UserMapper.getUserList",user);
}
public SqlSessionTemplate getSqlSession() {
return sqlSession;
}
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
}
3、UserMapper文件:
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bdqn.dao.user.UserMapper">
<select id="getUserList" resultType="User" parameterType="User">
SELECT * FROM `smbms_user`
<where>
<if test="userName!=null and userName!='' ">
and userName LIKE CONCAT('%',#{userName},'%')
</if>
<if test="userRole!=null">
AND `userRole` =#{userRole}
</if>
</where>
</select>
</mapper>
创建service层接口、实现类
package com.bdqn.service;
import java.util.List;
import com.bdqn.pojo.User;
public interface UserService {
List<User> findUserList(User user) throws Exception;
}
Service实现类:
package com.bdqn.service;
import java.util.List;
import com.bdqn.dao.user.UserMapper;
import com.bdqn.pojo.User;
public class UserServiceImpl implements UserService {
private UserMapper userMapper;
@Override
public List<User> findUserList(User user) throws Exception {
try {
return userMapper.getUsers(user);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
}
在resource文件夹中编写mybatis-config.xml
<?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>
<!-- 类型别名 -->
<typeAliases>
<package name="com.bdqn.pojo"/>
</typeAliases>
</configuration>
在resource文件夹中编写applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 获得sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 映射数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 映射mybatis核心配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!-- 映射mapper文件 -->
<property name="mapperLocations">
<list>
<value>classpath:com/bdqn/dao/**/*.xml</value>
</list>
</property>
</bean>
<!-- 获得sqlSession -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<bean id="UserMapper" class="com.bdqn.dao.user.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
<bean id="UserService" class="com.bdqn.service.UserServiceImpl">
<property name="userMapper" ref="UserMapper"/>
</bean>
</beans>
在test编写测试方法: