Spring

1.    Spring简介

1.1. Spring是什么

Spring 春天的意思。

Spring是分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架

Java EE

ejb

一站式:

* Spring框架有对三层的每层解决方案:

* web层:Spring MVC.

* 持久层: JDBCTemplate   dbutils

* 业务层:Spring的Bean管理.

IOC AOP

与框架的整合(ssm,ssh)

1.2. Spring的优点

方便解耦,简化开发

   Spring就是一个大工厂,可以将所有对象创建和依赖关系维护,交给Spring管理

AOP编程的支持

   Spring提供面向切面编程,可以方便的实现对程序进行权限拦截、运行监控等功能

声明式事务的支持

   只需要通过配置就可以完成对事务的管理,而无需手动编程

方便程序的测试

  Spring对Junit4支持,可以通过注解方便的测试Spring程序

方便集成各种优秀框架

 Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如:Struts2、Hibernate、MyBatis、Quartz等)的直接支持

降低JavaEE API的使用难度

Spring 对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等),都提供了封装,使这些API应用难度大大降低

 

JavaMail: 发送邮件。

Excel:导入导出。

 

Spring主要作用:整合其他框架

 

1.3. Spring的核心

1.3.1.  IOC

(Inverse of Control 反转控制)

B b = new B();

创建对象交由spring容器创建,我们只需要用就可以了

 

public class B{

 private A a;

}

 

 控制反转:,控制权的转移,应用程序本身不负责对象的创建和维护,而是由外部容器(spring)负责创建和维护。

 

将对象的创建权,交由Spring完成.

 

从现象来看,就是创建对象不用使用new。直接使用引用就可以获得对象.

 

 

 

案例分析:

   房屋中介      IOC

1.3.2.  AOP 

 aspectj

 

Aspect OrientedProgramming)面向切面编程

 

   主要功能:日志记录,性能统计,安全控制,事务处理异常处理等等

 

  aop可以理解为方法级别的过滤器

    

1.4. Spring的体系结构

Springboot----习惯大于配置

Springcloud----微服务

 

2.    入门示例

2.1. Spring的包介绍

 

Spring插件的安装

Jdk1.8 -----> spring4

Jdk1.7 ------>spring3

2.2. 案例代码

1.导入jar包

包的解释:

spring-beans-3.2.4.RELEASE.jar: Spring对配置bean的支持包,用于获得设置context的对象

spring-context-3.2.4.RELEASE.jar  Spring对象容器包-->对象容器

spring-core-3.2.4.RELEASE.jar  Spring的核心支持包

spring-expression-3.2.4.RELEASE.jar Spring表达式支持包-->用于xml文件的表达式

commons-logging-1.1.3.jar:日志处理

 

2.创建接口和实现类

 

3.创建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"

         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

 

<!-- 配置bean

  id: 这个bean的唯一标识

  class:对应的类

-->

<bean id="userDao" class="com.ys.dao.impl.UserDaoImpl02">

</bean>

</beans>

 

 

4.测试

 

3.    DI(依赖注入)

依赖:

 Public class B{

  Private A a;

 }

依赖注入:

  在创建B,给a实例化并赋值。

 

4.    注入方式

4.1. 构造器注入

 

 

4.2. Setter注入

 

4.2.1.  P名称空间注入

1.引入p名称空间的约束

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:p="http://www.springframework.org/schema/p"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

2.使用

<!-- p名称空间注入方式 -->

<bean id="userP" class="com.ys.entity.User" p:username="userConstructor"  p:password="1234567890"></bean>

 

 

4.2.2.  spEl注入

实体类代码

package com.ys.entity;

 

publicclass User {

    private String username;

    private String password;

    public User() {

    }

    public User(String username, String password) {

        this.username = username;

        this.password = password;

    }

    public String getUsername() {

        returnusername;

    }

    publicvoid setUsername(String username) {

        this.username = username;

    }

    public String getPassword() {

        returnpassword;

    }

    publicvoid setPassword(String password) {

        this.password = password;

    }

    @Override

    public String toString() {

        return"User [username=" + username + ", password=" + password + "]";

    }

}

 

配置文件代码

<!-- SpEL 注入方式 -->

<bean id="userSpEL" class="com.ys.entity.User">

  <property name="username" value="#{'zhangsan'}"></property>

  <property name="password" value="#{'12345678'}"></property>

</bean>

 

<bean id="userSpEL02" class="com.ys.entity.User">

  <property name="username" value="#{userConstructor.getUsername()}"></property>

  <property name="password" value="#{userConstructor.password}"></property>

</bean>

 

 

4.2.3.  集合的注入

实体类代码

package com.ys.collection;

 

import java.util.List;

import java.util.Map;

import java.util.Set;

 

//集合注入方式

public class CollectionBean {

        

         private List<String> list;

         private Set<String> set;

         private Map<String,String> maps;

 

         public void setList(List<String> list) {

                   this.list = list;

         }

         public void setSet(Set<String> set) {

                   this.set = set;

         }

         public void setMaps(Map<String, String> maps) {

                   this.maps = maps;

         }

         @Override

         public String toString() {

                   return "CollectionBean [list=" + list + ", set=" + set + ", maps=" + maps + "]";

         }

}

配置文件代码

<!-- 注入参数为集合-->

<!-- list集合 -->

<bean id="collectionBeanList" class="com.ys.collection.CollectionBean">

<!-- List集合参数 -->

  <property name="list">

      <list>

         <value>1</value>

         <value>2</value>

         <value>3</value>

      </list>

  </property>

  <!-- Set集合参数 -->

  <property name="set">

    <set>

      <value>1</value>

      <value>1</value>

      <value>2</value>

    </set>

  </property>

  <!--Map集合参数 -->

  <property name="maps">

  <map>

    <entry key="username" value="123456789"></entry>

    <entry key="password" value="0987654321"></entry>

  </map>

  </property>

</bean>

 

 

5.    Bean的生命周期

   初始化:1.InitializingBean接口,2.配置init-method

   销毁:1.DisposableBean接口,2.destroy-method

   配置全局的:default-init-method=""default-destroy-method=""

<!-- 配置spring容器要管理的bean

     init-method:  指定bean初始化时调用的方法

     destroy-method指定bean销毁时调用的方法

 -->

<bean id="userFuwu" class="com.ys.service.UserService" init-method="init" destroy-method="destroy"></bean>

 

Bean的代码

/**

 * Bean的生命周期

 *   1.初始化

 *   2.销毁

 */

publicclass UserService{

   

//  public UserService(){}

   

    publicvoid init(){

        System.out.println("UserService 初始化  init");

    }

   

    publicvoid login(){

        System.out.println("用户登录的Service");

    }

 

    publicvoid destroy(){

        System.out.println("UserService 销毁  destroyBean");

    }

}

 

6.    Bean的作用域

   singleton:单例,指一个Bean容器中只存在一份。

         prototype:  每次请求创建新的实例,destroy方法不生效。

         request:每次http请求创建一个实例且仅在当前request内有效  request.setAttribute();

         session:  每次http请求创建一个实例且仅在当前session内有效  session.setAttribute();

<!-- Bean的作用域

   scope:

      singleton 单例(默认)

      prototype 每次获取时都会创建一个新的

      request   bean设置到request作用域中,request.setAttribute()

      session  bean设置到session作用域中,session.setAttribute()

 -->

<bean id="userService" class="com.ys.service.UserService" scope="singleton"></bean>

 

 

7.    bean的自动装配(Autowiring)

 NO:不做任何操作

 byname:根据属性名自动匹配

 byType:根据属性的类型自动装配

 Constructor: 与byType方式类似

 

配置文件

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="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-3.2.xsd"

    default-autowire="byName">

<!--

  自动装配的方式:

    no/default:不自动装配

    byName:据属性名自动匹配

    byType: 根据属性的类型自动装配

    Constructor: 通过构造方法的方式注入,byType方式类似

 -->

<bean id="userService" class="com.ys.service.UserService"></bean>

 

<bean id="userDao" class="com.ys.dao.UserDao"></bean>

 

</beans>

 

代码

/**

 * Bean的生命周期

 *   1.初始化

 *   2.销毁

 */

publicclass UserService{

 

    private UserDao userDao;

    public UserService() {

    }

    public UserService(UserDao test){

        this.userDao = test;

        System.out.println("---UserService--");

    }

    publicvoid setUserDao(UserDao userDao) {

        System.out.println("--------setUserDao-------");

        this.userDao = userDao;

    }

    publicvoid login(){

        System.out.println("用户登录的Service");

        userDao.login();

    }

}

 

 

8.    IOC与DI的区别

IOC:控制反转:将对象的创建权,由Spring管理.

DI:依赖注入:在Spring创建对象的过程中,把对象依赖的属性注入到类中.

 

 

注意事项:

  Spring3.x   ------->  jdk1.7-(jdk1.7以下)

  Spring4.x   ------->  jdk1.8+

 

Spring包下载地址:

http://repo.spring.io/release/org/springframework/spring/

9.    AOP

9.1. 什么是AOP

面向切面编程

 

 

AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码(性能监视、事务管理、安全检查、缓存)

 Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码

 AspecJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入。

 

 

 

 

9.2. AOP原理

动态代理

  JDK动态代理:对实现了接口的类生成代理

 CGLib代理机制:对类生成代理

 

理解:方法级别的过滤器

Filter  拦截对应的请求       url     /login,/*

AOP   对方法进行增强      方法      拦截规则

     

注意事项:

  Aop需要IOC支持

Aop:

   1. 要处理的方法

   2. 处理什么方法

   3. 怎么处理

 

9.3. AOP表达式

execution的格式:

           execution(<访问修饰符>?<返回类型><方法名>(<参数>)<异常>)

                   表达式value:

                             execution("* com.ys.service.*(..)") --只检索当前包

                             execution("* com.ys.service..*(..)") --检索包及当前子包

                             execution("* com.ys.servie.UserService+.*(..)") --检索当前service以及其子类

                             execution("* save*(..)") --检索save开头的方法

 

9.4. AOP术语

   Joinpoint(连接点):被拦截的点,指的是具体的方法

         Pointcut(切入点):被拦截的方法,拦截的规则

         Advice(通知/增强):拦截之后要做的事

            前置通知,后置通知,异常通知,最终通知,环绕通知

         Aspect(切面)   :  做相应处理的类(DoWhat.java)

         Target(目标对象) :拦截的方法的类(方法对应的类,addUser()  UserService)

         Weaving(织入)

 

9.5. AOP使用

导入jar包

 

 

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:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd

        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

 

   <!-- 扫描注解 -->

  <context:component-scan base-package="com.ys"></context:component-scan>

 

  <!-- 配置aop -->

  <aop:config>

     <!-- 配置切面 -->

     <aop:aspect ref="myXmlAspect">

         <!-- 定义切入点 -->

         <aop:pointcut expression="execution(public void delete(..))" id="deletePointcut"/>

         <!-- 前置增强 -->

         <aop:before method="beforeMethod" pointcut-ref="deletePointcut"/>

         <!-- 后置增强 -->

         <aop:after-returning method="afterReturning" pointcut-ref="deletePointcut"/>

         <!-- 异常增强

           throwing:定义异常的名字,必须与增强方法(afterThrowing)的参数名一致

         -->

         <aop:after-throwing method="afterThrowing" pointcut-ref="deletePointcut" throwing="th"/>

         <!-- 最终增强 -->

         <aop:after method="afterMethod" pointcut-ref="deletePointcut"/>

         <!-- 环绕增强 -->

         <aop:around method="aroundMethod" pointcut="execution(* com.ys.service.AopService.update(String))"/>

         <!-- 后置增强获取返回值 -->

         <aop:after-returning method="afterHaveReturn" returning="returnVal" pointcut="execution(* com.ys.service.AopService.insert(..))"/>

     </aop:aspect>

  </aop:config>

</beans>

 

 

 

切面类的代码

package com.ys.aspect;

 

import java.util.Arrays;

 

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.Signature;

import org.springframework.stereotype.Component;

 

/**

 * 使用xml方式配置切面

 * @author Administrator

 *

 */

@Component("myXmlAspect")

public class MyXmlAspect {

        

         public void beforeMethod(){

                   System.out.println("调用方法之前调用。。。。。。。。。。。。。。。。。。。。");

         }

        

         public void afterReturning(){

                   System.out.println("调用方法之后调用。。。。。。。。。。。。");

         }

        

         public void afterThrowing(Throwable th){

                   System.out.println("异常之后调用。。。。。。。。。。。。。。。。。。。。。");

                   th.printStackTrace();

         }

        

         public void afterMethod(){

                   System.out.println("最终增强。。。。。。。。。。。。");

         }

        

         public void aroundMethod(ProceedingJoinPoint joinPoint){

                   try {

                            System.out.println("环绕之前");

                            //获取传入参数

                            Object[] args = joinPoint.getArgs();

                            System.out.println(Arrays.toString(args));

                            //获取到目标对象

                            Object target = joinPoint.getTarget();

                            System.out.println("目标对象为:"+target);

                            //获取方法的签名

                            Signature signature = joinPoint.getSignature();

                            System.out.println("增强方法的签名:"+signature);

                            //放行

                            joinPoint.proceed();

                            System.out.println("环绕之后");

                  } catch (Throwable e) {

                            e.printStackTrace();

                   }

         }

        

         public void afterHaveReturn(Object returnVal){

                   System.out.println("后置增强: "+returnVal);

         }

 

}

 

 

 

10.            注解的使用

10.1.   IOC和DI

 

  @Component是一个通用注解,可用于任何的bean

         @Repository,@Service,@Controller是有针对性的注解

         @Repository通常用于注解DAO类,持久层

         @Service  通常用于注解Serive,业务层

         @Controller通常用于Controller类,即控制层(MVC)

 

 

 @Autowired

 @Qualifier

 @Resource

 

注解使用步骤:

1.在对应的类上使用@Component,@Repository,@Service,@Controller其中一个注解

  该bean的默认标识为类名首字母小写

2.需要在配置文件包扫描

<?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:context="http://www.springframework.org/schema/context"

         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd

                   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

 

<!-- 使用注解的时候,需要扫描包

   base-package:要扫描的包

-->

<context:component-scan base-package="com.ys"></context:component-scan>

</beans>

 

这样对应的对象会由spring来创建。

 

那么如何注入对象中的属性呢?

1.普通属性

 @Value

2.引用属性

 @Autowired

 @Qualifier

 @Resource(name=”名字”)

 

示例代码

 

10.2.  AOP

配置文件

<?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"

    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/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

 

<!-- 配置扫描包 -->

<context:component-scan base-package="com.ys"></context:component-scan>

 

<!-- 使用注解配置Aop的配置 -->

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

 

</beans>

 

 

切面类

package com.ys.aspect;

 

import org.aspectj.lang.JoinPoint;

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.Around;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Before;

import org.aspectj.lang.annotation.Pointcut;

import org.springframework.stereotype.Component;

 

/**

 * 切面类

 * 使用@Aspect注解告诉spring这是一个切面类

 *

 * @Before

 * @AfterReturning

 * @AfterThrowing

 * @After

 * @Around

 *

 */

@Component

@Aspect

public class MyAnnotationAspect {

        

         @Pointcut(value="execution(* com.ys.service.AopService.update(..))")

         public void mypointcut(){}

        

         @Before("mypointcut()")

         public void pointcutTest(){

                   System.out.println("pointcut..........................");

         }

        

         //前置增强

         @Before("execution(* com.ys.service.AopService.delete(..))")

         public void before(JoinPoint joinPoint){

                   System.out.println("前置增强--注解");

         }

         //后置增强

         @AfterReturning("execution(* com.ys.service.AopService.delete(..))")

         public void afterReturning(){

                   System.out.println("后置增强---注解");

         }

         //最终增强

         @After("execution(* com.ys.service.AopService.delete(..))")

         public void after(){

                   System.out.println("最终增强");

         }

        

         //异常增强

         @AfterThrowing("execution(* com.ys.service.AopService.delete(..))")

         public void afterThrowing(){

                   System.out.println("异常增强");

         }

         //环绕增强

         @Around("execution(* com.ys.service.AopService.delete(..))")

         public void aroundMethod(ProceedingJoinPoint joinPoint){

                   try {

                            System.out.println("环绕增强前");

                            //放行

                            joinPoint.proceed();

                            System.out.println("环绕增强后");

                   } catch (Throwable e) {

                            e.printStackTrace();

                   }

                  

         }

}

 

 

11.            Spring与mybatis整合

11.1.  导入jar包

除了基础jar包之外的包

 mybatis-spring-1.2.0.jar

 spring-jdbc-4.2.6.RELEASE.jar

 spring-tx-4.2.6.RELEASE.jar

11.2.  配置步骤

引入外部属性文件

 1.使用context标签

<!-- 引入外部属性文件 -->

<context:property-placeholder  location="database.properties"/>

 

 2.使用bean加载的方式

 <!-- 2.通过bean的方式引入外部属性文件 -->

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

   <property name="location" value="database.properties"></property>

 </bean>

 

 

11.2.1.          配置数据源

1.配置spring内置数据源

 <!-- 配置Spring内置数据源

    spring-jdbc-4.2.6.RELEASE.jar jar包中

 -->

 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

     <!-- 配置连接数据库的四个基本要素 -->

     <property name="driverClassName" value="${jdbc.driver}"></property>

     <property name="url" value="${jdbc.url}"></property>

     <property name="username" value="${jdbc.username}"></property>

     <property name="password" value="${jdbc.password}"></property>

 </bean>

2.配置c3p0数据源

<!-- 配置c3p0数据源 -->

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

  <!-- 配置基本四要素 -->

  <property name="driverClass" value="${jdbc.driver}"></property>

  <property name="jdbcUrl" value="${jdbc.url}"></property>

  <property name="user" value="${jdbc.username}"></property>

  <property name="password" value="${jdbc.password}"></property>

</bean>

 

11.2.2.          配置sqlSessionFactoryBean

代替mybatis-config.xml

 <!-- 配置SqlSessionFactoryBean 代替mybatis-config.xml配置文件-->

   <bean class="org.mybatis.spring.SqlSessionFactoryBean">

      <!-- 注入数据源 -->

      <property name="dataSource" ref="dataSource"></property>

      <!-- 由于mapper.javamapper.xml在同一个包下且名字相同,可以省略映射文件的配置 -->

      <!--

         com/ys/**/*.xml

                     找到com.ys包下的xml文件

       -->

      <property name="mapperLocations" value="com/ys/**/*.xml"></property>

      <!--  配置别名 -->

      <property name="typeAliasesPackage" value="com.ys.entity"></property>

   </bean>

 

 

11.2.3.          配置mapper

1.使用MapperScannerConfigurer进行包扫描

   <!-- 扫描mapper.java -->

   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <!-- 配置包扫描 -->

         <property name="basePackage" value="com.ys.mapper"></property>

   </bean>

 

 

2.使用MapperFactoryBean进行mapper的创建

<!-- 使用MapperFactoryBean的方式配置Mapper.java -->

<bean id="userYinshe" class="org.mybatis.spring.mapper.MapperFactoryBean">

   <property name="mapperInterface" value="com.ys.mapper.UserMapper"></property>

   <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>

</bean>

 

 

 

 

11.2.4.          完整的applicationContext.xml配置文件

1.MapperScannerConfigurer加载bean的方式

<?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: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-4.2.xsd">

 

<!-- 配置数据源

<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:3307/spring_transaction_demo"></property>

    <property name="username" value="root"></property>

    <property name="password" value="root"></property>

</bean>

-->

<!-- 1.引用外部的属性文件 -->

 

<context:property-placeholder location="database.properties"/>

 

 <!-- 2.通过bean的方式引入外部属性文件 -->

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

   <property name="location" value="database.properties"></property>

 </bean>

 

<!-- 配置数据源 -->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <!-- 连接数据库的四个基本要素 -->

    <property name="driverClassName" value="${jdbc.driver}"></property>

    <property name="url" value="${jdbc.url}"></property>

    <property name="username" value="${jdbc.username}"></property>

    <property name="password" value="${jdbc.password}"></property>

</bean>

 

 

<!-- spring负责 SqlSessionFactoryBean的创建 -->

<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">

    <!-- 配置数据源 -->

    <property name="dataSource" ref="dataSource"></property>

    <!-- 配置映射文件 -->

    <property name="mapperLocations" value="com/ys/mapper/xml/UserMapper.xml"></property>

    <!-- 配置别名  使用包扫描

      <property name="typeAliasesPackage" value="com.ys.entity"></property>

    -->

   

    <!-- 引入mybatis的核心配置文件 -->

    <property name="configLocation" value="classpath:mybatis-config.xml"></property>

   

</bean>

 

<!-- 配置mapper.xml的扫描 -->

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

    <!-- 配置要扫描的包 -->

    <property name="basePackage" value="com.ys.mapper"></property>

</bean>

 

</beans>

 

2.MapperFactoryBean的方式

<?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: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-4.2.xsd">

 

 

<!-- 1.引用外部的属性文件

<context:property-placeholder location="database.properties"/>

 -->

 

 <!-- 2.通过bean的方式引入外部属性文件 -->

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

   <property name="location" value="database.properties"></property>

 </bean>

 

<!-- 配置数据源 -->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <!-- 连接数据库的四个基本要素 -->

    <property name="driverClassName" value="${jdbc.driver}"></property>

    <property name="url" value="${jdbc.url}"></property>

    <property name="username" value="${jdbc.username}"></property>

    <property name="password" value="${jdbc.password}"></property>

</bean>

 

<!-- spring负责 SqlSessionFactoryBean的创建 -->

<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">

    <!-- 配置数据源 -->

    <property name="dataSource" ref="dataSource"></property>

    <!-- 配置映射文件路径 -->

    <property name="mapperLocations" value="com/ys/mapper/**/*Mapper.xml"></property>

    <!-- 配置别名 -->

    <property name="typeAliasesPackage" value="com.ys.entity"></property>

</bean>

 

<!-- 使用MapperFactoryBean的方式配置Mapper.java -->

<bean id="userYinshe" class="org.mybatis.spring.mapper.MapperFactoryBean">

   <property name="mapperInterface" value="com.ys.mapper.UserMapper"></property>

   <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>

</bean>

 

</beans>

 

 

 

1.测试:

@Test

    publicvoid test(){

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserMapper userMapper=(UserMapper)applicationContext.getBean("userMapper");

        List<User> list = userMapper.findByName("");

        System.out.println(list);

    }

 

12.            Spring控制事务

12.1.  导入相应的jar包

 

12.2.  使用配置文件的方式

1.在配置文件中配置事务管理器

2.定义增强的事务

3.使用aop对相应的方法进行增强

<!-- spring声明式事务配置 -->

<!-- 配置事务管理器 -->

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

    <property name="dataSource" ref="dataSource"></property>

</bean>

 

<!-- 定义事务增强

     在配置增强时,如果事务管理器的标识(Id)为transactionManager可以省略如下代码:

         transaction-manager="transactionManager"

-->

<tx:advice id="txAdivice">

   <!-- 配置相应的属性 -->

  <tx:attributes>

        <!-- 对应方法的属性设置

          name:方法的名字

          isolation: 隔离级别

             串行化(Serializable

             重复读(Repeatable read)

             读已提交(Read committed)

             读未提交(Read uncommitted)

          propagation:传播行为

                REQUIRED如果有则使用当前事务,没有则创建新的事务

                REQUIRED_NEW不使用当前事务,创建新事务

                SUPPORTS支持当前事务,不存在则不使用事务

         -->

       <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED"/>

  </tx:attributes>

</tx:advice>

 

<!-- 对相应方法进行增强 -->

<aop:config>

   <!-- 定义切入点 -->

    <aop:pointcut expression="execution(* com.ys.service.UserService+.*(..))" id="mypointcut"/>

    <!-- 增强 -->

    <aop:advisor advice-ref="txAdivice" pointcut-ref="mypointcut"/>

</aop:config>

 

 

12.3.  使用注解的方式

1.配置文件中开启注解管理事务

<!-- spring声明式事务配置 -->

<!-- 配置事务管理器 -->

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

    <property name="dataSource" ref="dataSource"></property>

</bean>

 

<!-- 配置注解管理事务 -->

<tx:annotation-driven transaction-manager="transactionManager"/>

 

 

2.在相应要添加事务的位置添加事务注解开启事务

13.            Spring整合junit4

导入jar包

 

 

使用junit4

 

14.            Spring整合web

导入jar包

在web.xml中配置加载spring配置文件

使用

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值