spring框架02

2018-05-02  本文已影响6人  RLM233

1 AOP面向切面编程

1.1 什么是AOP

1.2 AOP实现原理

1.3 AOP术语

AOP示例图

2 JDK动态代理

2.1 接口和实现类

public interface UserService {
    public void addUser();
    public void updateUser();
    public void deleteUser();
}
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("添加");
    }

    @Override
    public void updateUser() {
        System.out.println("修改");
    }

    @Override
    public void deleteUser() {
        System.out.println("删除");
    }
}

2.2 切面类

public class MyAspect {
    public void before(){
        System.out.println("前方法");
    }
    
    public void after(){
        System.out.println("后方法");
    }
}

2.3 代理类

public class MyBeanFactory {
    public static UserService createService(){
        //1.目标类
        final UserService userService = new UserServiceImpl();
        //2.切面类
        final MyAspect myAspect = new MyAspect();
        /* 3.代理类:将目标类(切入点)和切面类(通知)结合,从而形成切面
         *      Proxy.newProxyInstance参数详解:
         *          参数1:loader,类加载器,动态代理类 运行时创建,任何类都需要类加载器将其加载到存储器
         *                  一般情况:当前类.class.getClassLoader();
         *                  目标类实例.getClass().get...
         *          参数2:Class[] interfaces 代理类需要实现的所有接口
         *                  目标类实例.getClass().getInterfaces()  ;注意:只能获得自己接口,不能获得父元素接口
         *          参数3:InvocationHandler是处理类;接口,必须进行实现类,一般采用匿名内部
         *               * 提供了invoke方法,代理类的每一个方法执行,都将调用一次invoke
         *                      参数1:Object proxy :代理对象
         *                      参数2:Method method : 代理对象当前执行的方法的描述对象(反射)
         *                          执行方法名:method.getName()
         *                          执行方法:method.invoke(对象,实际参数)
         *                      参数3:Object[] args :方法实际参数
         */
        
        UserService proxyInstance = (UserService) Proxy.newProxyInstance(MyBeanFactory.class.getClassLoader(), 
                               userService.getClass().getInterfaces(), 
                               new InvocationHandler() {
                                @Override
                                public Object invoke(Object proxy, Method method, Object[] arg2)
                                        throws Throwable {
                                    //前方法
                                    myAspect.before();
                                    //执行目标类方法
                                    Object obj = method.invoke(userService, arg2);
                                    //后方法
                                    myAspect.after();
                                    return obj;
                                }
                            });
        return proxyInstance;
    }
}

2.4 测试

@org.junit.Test
public void test01(){
    UserService userService = MyBeanFactory.createService();
    userService.addUser();
}

2.5 运行结果

前方法
添加
后方法

3 CGLIB字节码增强

3.1 创建实现类

public class UserServiceImpl {

    public void addUser() {
        System.out.println("添加");
    }

    public void updateUser() {
        System.out.println("修改");
    }

    public void deleteUser() {
        System.out.println("删除");
    }
}

3.2 代理类

public class MyBeanFactory {
    public static UserServiceImpl createService(){
        // 1.目标类
        final UserServiceImpl userService = new UserServiceImpl();
        // 2.切面类
        final MyAspect myAspect = new MyAspect();
        // 3.代理类,采用cglib,底层创建目标类的子类
        // 3.1  核心类
        Enhancer enhancer = new Enhancer();
        // 3.2 确定父类
        enhancer.setSuperclass(userService.getClass());
        /* 3.3 设置回调函数,MethodInterceptor接口等效 jdk InvocationHandler接口
         *    intercept() 等效 jdk invoke();
         *    参数1、参数2、参数3:以invoke一样
         *    参数4:methodProxy 方法的代理
         */
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] arg2,
                    MethodProxy arg3) throws Throwable {
                //前方法
                myAspect.before();
                //执行目标类方法
                Object obj = method.invoke(userService, arg2);
                //后方法
                myAspect.after();
                return obj;
            }
        });
        // 3.4 创建代理
        UserServiceImpl proxService = (UserServiceImpl) enhancer.create();
        return proxService;
    }
}

3.3 测试类

@org.junit.Test
public void test01(){
     UserServiceImpl userServiceImpl = MyBeanFactory.createService();
     userServiceImpl.addUser();
}

4 AOP联盟通知类型

5 spring aop半自动代理

5.1 接口和实现类

public interface UserService {
    public void addUser();
    public void updateUser();
    public void deleteUser();
}
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("添加");
    }

    @Override
    public void updateUser() {
        System.out.println("修改");
    }

    @Override
    public void deleteUser() {
        System.out.println("删除");
    }
}

5.2 切面类

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
 * 采用“环绕通知” MethodInterceptor
 */
public class MyAspect implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
        System.out.println("前方法");
        //手动执行目标方法
        Object object = mi.proceed();
        System.out.println("后方法");
        return object;
    }
}

5.3 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.xsd">

    <!-- 1 创建目标类 -->
    <bean id="UserServiceImplId" class="spring_aop03.UserServiceImpl"></bean>
    <!-- 2 创建切面类 -->
    <bean id="myAspectId" class="spring_aop03.MyAspect"></bean>
    
    <!-- 3 创建代理类 
        * 使用工厂bean FactoryBean ,底层调用 getObject() 返回特殊bean
        * ProxyFactoryBean 用于创建代理工厂bean,生成特殊代理对象
            interfaces : 确定接口们
                通过<array>可以设置多个值
                只有一个值时,value=""
            target : 确定目标类
            interceptorNames : 通知 切面类的名称,类型String[],如果设置一个值 value=""
            optimize :强制使用cglib
                <property name="optimize" value="true"></property>
        底层机制
            如果目标类有接口,采用jdk动态代理
            如果没有接口,采用cglib 字节码增强
            如果声明 optimize = true ,无论是否有接口,都采用cglib
        
    -->
    <bean id="proxyServiceId" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="interfaces" value="spring_aop03.UserService"></property>
        <property name="target" ref="UserServiceImplId"></property>
        <property name="interceptorNames" value="myAspectId"></property>
    </bean>
</beans>

5.4 测试

@org.junit.Test
public void test01(){
    String xmlPath = "spring_aop03/applicationContext.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
    //获得代理类
    UserService userService = (UserService) applicationContext.getBean("proxyServiceId");
    userService.addUser();
    }

6 spring aop全自动

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

    <!-- 1 创建目标类 -->
    <bean id="userServiceImplId" class="spring_aop04.UserServiceImpl"></bean>
    <!-- 2 创建切面类 -->
    <bean id="myAspectId" class="spring_aop04.MyAspect"></bean>
    
    <!-- 3 aop编程 
        3.1 导入命名空间
        3.2 使用 <aop:config>进行配置
                proxy-target-class="true" 声明时使用cglib代理
            <aop:pointcut> 切入点 ,从目标对象获得具体方法
            <aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
                advice-ref 通知引用
                pointcut-ref 切入点引用
        3.3 切入点表达式
            execution(* com.itheima.c_spring_aop.*.*(..))
            选择方法         返回值任意   包             类名任意   方法名任意   参数任意
    -->
    <aop:config proxy-target-class="true">
        <aop:pointcut expression="execution(* spring_aop04.*.*(..))" id="myPointCut"/>
        <aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
    </aop:config>
</beans>

6.2 测试

@org.junit.Test
public void test01(){
    String xmlPath = "spring_aop04/applicationContext.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
    //获得代理类
    UserService userService = (UserService) applicationContext.getBean("userServiceImplId");
    userService.addUser();
}

7 AspectJ

7.1 介绍

7.2 切入点表达式

public      公共方法
*           任意
void      返回没有值
String    返回值字符串
*         任意
com.itheima.crm             固定包
com.itheima.crm.*.service   crm包下面子包任意 (例如:com.itheima.crm.staff.service)
com.itheima.crm..           crm包下面的所有子包(含自己)
com.itheima.crm.*.service.. crm包下面任意子包,固定目录service,service目录任意包
UserServiceImpl         指定类
*Impl                   以Impl结尾
User*                   以User开头
*                       任意
addUser                 固定方法
add*                    以add开头
*Do                     以Do结尾
*                       任意
()                          无参
(int)                       一个整型
(int ,int)                  两个
(..)                        参数任意
综合1
    execution(* com.itheima.crm.*.service..*.*(..))
综合2
    <aop:pointcut expression="execution(* com.itheima.*WithCommit.*(..)) || 
                          execution(* com.itheima.*Service.*(..))" id="myPointCut"/>
2.within:匹配包或子包中的方法
    within(com.itheima.aop..*)
3.this:匹配实现接口的代理对象中的方法
    this(com.itheima.aop.user.UserDAO)
4.target:匹配实现接口的目标对象中的方法
    target(com.itheima.aop.user.UserDAO)
5.args:匹配参数格式符合标准的方法
    args(int,int)
6.bean(id)  对指定的bean所有的方法
    bean('userServiceId')

7.3 AspectJ通知类型

8 AspectJ示例(基于xml)

8.1 接口和实现类

public interface UserService {
    
    public void addUser();
    public String updateUser();
    public void deleteUser();
}
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("d_aspect.a_xml addUser");
    }

    @Override
    public String updateUser() {
        System.out.println("d_aspect.a_xml updateUser");
        int i = 1/ 0;
        return "hello";
    }

    @Override
    public void deleteUser() {
        System.out.println("d_aspect.a_xml deleteUser");
    }
}

8.2 切面类

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 切面类,含有多个通知
 */
public class MyAspect {
    
    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }
    
    public void myAfterReturning(JoinPoint joinPoint,Object ret){
        System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
    }
    
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("前");
        //手动执行目标方法
        Object obj = joinPoint.proceed();
        
        System.out.println("后");
        return obj;
    }
    
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
        System.out.println("抛出异常通知 : " + e.getMessage());
    }
    
    public void myAfter(JoinPoint joinPoint){
        System.out.println("最终通知");
    }
}

8.3 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">
    <!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.itheima.d_aspect.a_xml.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.itheima.d_aspect.a_xml.MyAspect"></bean>
    <!-- 3 aop编程 
        <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
            ref 切面类引用
        <aop:pointcut> 声明一个切入点,所有的通知都可以使用。
            expression 切入点表达式
            id 名称,用于其它通知引用
    -->
    <aop:config>
        <aop:aspect ref="myAspectId">
            <aop:pointcut expression="execution(* com.itheima.d_aspect.a_xml.UserServiceImpl.*(..))" id="myPointCut"/>
            
            <!-- 3.1 前置通知 
                <aop:before method="" pointcut="" pointcut-ref=""/>
                    method : 通知,及方法名
                    pointcut :切入点表达式,此表达式只能当前通知使用。
                    pointcut-ref : 切入点引用,可以与其他通知共享切入点。
                通知方法格式:public void myBefore(JoinPoint joinPoint){
                    参数1:org.aspectj.lang.JoinPoint  用于描述连接点(目标方法),获得目标方法名等
                例如:
            <aop:before method="myBefore" pointcut-ref="myPointCut"/>
            -->
            
            <!-- 3.2后置通知  ,目标方法后执行,获得返回值
                <aop:after-returning method="" pointcut-ref="" returning=""/>
                    returning 通知方法第二个参数的名称
                通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){
                    参数1:连接点描述
                    参数2:类型Object,参数名 returning="ret" 配置的
                例如:
            <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
            -->
            
            <!-- 3.3 环绕通知 
                <aop:around method="" pointcut-ref=""/>
                通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
                    返回值类型:Object
                    方法名:任意
                    参数:org.aspectj.lang.ProceedingJoinPoint
                    抛出异常
                执行目标方法:Object obj = joinPoint.proceed();
                例如:
            <aop:around method="myAround" pointcut-ref="myPointCut"/>
            -->
            <!-- 3.4 抛出异常
                <aop:after-throwing method="" pointcut-ref="" throwing=""/>
                    throwing :通知方法的第二个参数名称
                通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
                    参数1:连接点描述对象
                    参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置
                例如:
            <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
            -->
            <!-- 3.5 最终通知 -->           
            <aop:after method="myAfter" pointcut-ref="myPointCut"/>
            
            
            
        </aop:aspect>
    </aop:config>
</beans>

8.4 测试

@Test
public void demo01(){
    String xmlPath = "com/itheima/d_aspect/a_xml/beans.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
    //获得目标类
    UserService userService = (UserService) applicationContext.getBean("userServiceId");
    userService.addUser();
    userService.updateUser();
    userService.deleteUser();
}

9 AspectJ示例(基于注解)

9.1 接口与实现类

public interface UserService {
    
    public void addUser();
    public String updateUser();
    public void deleteUser();
}
@Service("userServiceId")
public class UserServiceImpl implements UserService {

    @Override
    public void addUser() {
        System.out.println("d_aspect.b_anno addUser");
    }

    @Override
    public String updateUser() {
        System.out.println("d_aspect.b_anno updateUser");
        int i = 1/ 0;
        return "Hello";
    }

    @Override
    public void deleteUser() {
        System.out.println("d_aspect.b_anno deleteUser");
    }
}

9.2 切面类

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;

/**
 * 切面类,含有多个通知
 */
@Component
@Aspect
public class MyAspect {
    
    //切入点当前有效
//  @Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }
    
    //声明公共切入点
    @Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    private void myPointCut(){
    }
    
//  @AfterReturning(value="myPointCut()" ,returning="ret")
    public void myAfterReturning(JoinPoint joinPoint,Object ret){
        System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
    }
    
//  @Around(value = "myPointCut()")
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("前");
        //手动执行目标方法
        Object obj = joinPoint.proceed();
        
        System.out.println("后");
        return obj;
    }
    
//  @AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
        System.out.println("抛出异常通知 : " + e.getMessage());
    }
    
    @After("myPointCut()")
    public void myAfter(JoinPoint joinPoint){
        System.out.println("最终通知");
    }
}

9.3 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.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- 1.扫描 注解类 -->
    <context:component-scan base-package="com.itheima.d_aspect.b_anno"></context:component-scan>
    
    <!-- 2.确定 aop注解生效 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

9.4 测试

@Test
public void demo01(){
    String xmlPath = "com/itheima/d_aspect/b_anno/beans.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
    //获得目标类
    UserService userService = (UserService) applicationContext.getBean("userServiceId");
    userService.addUser();
    userService.updateUser();
    userService.deleteUser();
}

10 JdbcTemplate

spring提供了JDBC JdbcTemplate操作数据库,使用前需先导入jdbc和事务的jar包


所需jar包

10.1 API方式操作

public class UserVo {
    public int id;
    public String name;
    public int money;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getMoney() {
        return money;
    }
    public void setMoney(int money) {
        this.money = money;
    }
}
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;

public class JdbcAPI {

    public static void main(String[] args) {
        // 创建数据库连接池
        BasicDataSource dataSource = new BasicDataSource();

        // 加载驱动、链接、用户名、密码
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/study");
        dataSource.setUsername("root");
        dataSource.setPassword("10086");
        
        // 创建JdbcTemplate模板
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        // 数据源注入模板
        jdbcTemplate.setDataSource(dataSource);
        
        // 通过AIP操作数据库
        jdbcTemplate.update("insert into account (name,money) values (?,?)", "jack","1000");
    }
}

10.2 DBCP连接池操作

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import cn.lm.entity.UserVo;

public class UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    public void update(UserVo user) {
        String sql = "update account set money=?,name=? where id=?";
        jdbcTemplate.update(sql,user.getMoney(),user.getName(),user.getId());
    }
    
    public void findUser(UserVo u) {
        String sql = "select * from account where id=?";
        RowMapper<UserVo> rowMapper = new BeanPropertyRowMapper<>(UserVo.class); 
        UserVo userVo = jdbcTemplate.queryForObject(sql,rowMapper,u.getId());
        System.out.println(userVo.getId()+"..."+userVo.getName()+"..."+userVo.getMoney());
    }
}
<?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.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 创建数据源 -->
    <bean id="dataSourceId" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/study"></property>
        <property name="username" value="root"></property>
        <property name="password" value="10086"></property>
    </bean>

    <!-- 创建模板 ,需要注入数据源-->
    <bean id="jdbcTemplateId" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSourceId"></property>
    </bean>
    
    <!-- 配置dao -->
    <bean id="userDaoId" class="cn.lm.dbcp.UserDao">
        <property name="jdbcTemplate" ref="jdbcTemplateId"></property>
    </bean>
</beans>  
public class Test {

    @org.junit.Test
    public void update() {
        UserVo user = new UserVo();
        user.setId(1);
        user.setName("刘能");
        user.setMoney(2000);
        
        String xmlPath = "cn/lm/dbcp/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
        //获得目标类
        UserDao userDao = (UserDao) applicationContext.getBean("userDaoId");
        userDao.update(user);
        //System.out.println(user.getId());
    }
    
    @org.junit.Test
    public void findUser() {
        UserVo user = new UserVo();
        user.setId(1);
        String xmlPath = "cn/lm/dbcp/applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
        //获得目标类
        UserDao userDao = (UserDao) applicationContext.getBean("userDaoId");
        userDao.findUser(user);
    }
}

10.3 C3P0连接池操作

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import cn.lm.entity.UserVo;

public class UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    public List<UserVo> findAll() {
        String sql = "select * from account";
        RowMapper<UserVo> rowMapper = new BeanPropertyRowMapper<>(UserVo.class);
        List<UserVo> list = jdbcTemplate.query(sql, rowMapper);
        return list;
    }
}
<?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.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 创建数据源 -->
    <bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/study"></property>
        <property name="user" value="root"></property>
        <property name="password" value="10086"></property>
    </bean>

    <!-- 创建模板 ,需要注入数据源-->
    <bean id="jdbcTemplateId" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSourceId"></property>
    </bean>
    
    <!-- 配置dao -->
    <bean id="userDaoId" class="cn.lm.c3p0.UserDao">
        <property name="jdbcTemplate" ref="jdbcTemplateId"></property>
    </bean>
</beans>  
@org.junit.Test
public void findAll() {
    UserVo user = new UserVo();
    user.setId(1);
    String xmlPath = "cn/lm/c3p0/applicationContext.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
    //获得目标类
    UserDao userDao = (UserDao) applicationContext.getBean("userDaoId");
    List<UserVo> list = userDao.findAll();
    for (UserVo userVo : list) {
        System.out.println(userVo.getId()+"..."+userVo.getName()+"..."+userVo.getMoney());
    }
}

10.4 JdbcDaoSupport

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import cn.lm.entity.UserVo;

public class UserDao extends JdbcDaoSupport{
    
    public List<UserVo> findAll() {
        String sql = "select * from account";
        RowMapper<UserVo> rowMapper = new BeanPropertyRowMapper<>(UserVo.class);
        List<UserVo> list = this.getJdbcTemplate().query(sql, rowMapper);
        return list;
    }
}
<?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.xsd
                           http://www.springframework.org/schema/aop 
                           http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 创建数据源 -->
    <bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/study"></property>
        <property name="user" value="root"></property>
        <property name="password" value="10086"></property>
    </bean>

    <!-- UserDao 继承 JdbcDaoSupport,之后只需要注入数据源,底层将自动创建模板 -->
    
    <!-- 配置dao -->
    <bean id="userDaoId" class="cn.lm.JdbcDaoSupport.UserDao">
        <property name="dataSource" ref="dataSourceId"></property>
    </bean>
</beans>  
@org.junit.Test
public void findAll() {
    UserVo user = new UserVo();
    user.setId(1);
    String xmlPath = "cn/lm/JdbcDaoSupport/applicationContext.xml";
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        
    //获得目标类
    UserDao userDao = (UserDao) applicationContext.getBean("userDaoId");
    List<UserVo> list = userDao.findAll();
    for (UserVo userVo : list) {
        System.out.println(userVo.getId()+"..."+userVo.getName()+"..."+userVo.getMoney());
    }
}

10.4 配置properties文件

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ee19_spring_day02
jdbc.user=root
jdbc.password=1234
<!-- 加载配置文件 
    "classpath:"前缀表示 src下
    在配置文件之后通过  ${key} 获得内容
-->
<context:property-placeholder location="classpath:com/itheima/f_properties/jdbcInfo.properties"/>
    
<!-- 创建数据源 c3p0-->
<bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driverClass}"></property>
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="user" value="${jdbc.user}"></property>
    <property name="password"  value="${jdbc.password}"></property>
</bean>
上一篇 下一篇

猜你喜欢

热点阅读