注意

  1. 实际企业开发中,纯xml模式使⽤已经很少了
  2. 引⼊注解功能,不需要引⼊额外的jar
  3. xml+注解结合模式,xml⽂件依然存在,所以,spring IOC容器的启动仍然从加载xml开始
  4. 哪些bean的定义写在xml中,哪些bean的定义使⽤注解
    第三⽅jar中的bean定义在xml,⽐如德鲁伊数据库连接池,⾃⼰开发的bean定义使⽤注解。(不绝对)

https://www.yuque.com/wuxiangwuwo/dfvedv/soxipg
使用之前的hua-transfer-ioc-xml项目,改造为hua-transfer-ioc-xml-anno项目。

一、纯xml改造为xml结合注解的形式

1 DataSource的bean配置为xml形式(第三方bean)

<!--第三方jar中的bean定义在xml中-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/bank"/>
    <property name="username" value="root"/>
    <property name="password" value="muZI5945@"/>
</bean>

删除DruidUtils类

2 改造自定义的bean(注解)

2.1 改造ConnectionUtils

@Component("connectionUtils")
public class ConnectionUtils {

    @Autowired
    private DataSource dataSource;

    // 存储当前线程的连接
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();


    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentThreadConn() throws SQLException {
        /**
         * 判断当前线程中是否已经绑定连接,如果没有绑定,
         * 需要从连接池获取一个连接绑定到当前线程
         */
        Connection connection = threadLocal.get();
        if(connection == null) {
            // 从连接池拿连接并绑定到线程
            connection = dataSource.getConnection();
            // 绑定到当前线程
            threadLocal.set(connection);
        }
        return connection;
    }
}

2.2 改造JdbcAccountDaoImpl

@Repository("accountDao")
public class JdbcAccountDaoImpl implements AccountDao {

    @Autowired
    private ConnectionUtils connectionUtils;

    // 无需connectionUtils的set方法
    // 省略部分代码
}

2.3 改造ProxyFactory类

@Component("proxyFactory")
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;

     // 省略下面代码   
}

2.4 改造AccountServiceImpl

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    // 最佳状态
    // @Autowired 按照类型注入 ,如果按照类型无法唯一锁定对象,
    //可以结合@Qualifier指定具体的id
    @Autowired
    @Qualifier("accountDao")
    private AccountDao accountDao;

    // 省略下面代码   
}

2.5 serlet类不变动

@WebServlet(name = "transferServlet", urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {
    private AccountService accountService = null;

    @Override
    public void init() throws ServletException {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getWebApplicationContext(this.getServletContext());
        ProxyFactory proxyFactory = 
            (ProxyFactory) webApplicationContext.getBean("proxyFactory");
        accountService = (AccountService) proxyFactory
            .getProxy(webApplicationContext.getBean("accountService"));
    }

2.6 改造TransactionManager

@Component("transactionManager")
public class TransactionManager {
    @Autowired
    private ConnectionUtils connectionUtils;
    // 省略部分代码
}

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

    <!--第三方jar中的bean定义在xml中-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/bank"/>
        <property name="username" value="root"/>
        <property name="password" value="muZI5945@"/>
    </bean>

    <bean id="accountService" class="com.hua.service.impl.AccountServiceImpl">
        <property name="AccountDao" ref="accountDao"></property>
    </bean>

    <bean id="accountDao" class="com.hua.dao.impl.JdbcAccountDaoImpl"
          scope="singleton" init-method="init" destroy-method="destory">
        <property name="ConnectionUtils" ref="connectionUtils"/>
    </bean>


    <!--配置新增的三个Bean-->
    <bean id="connectionUtils" class="com.hua.utils.ConnectionUtils"></bean>

    <!--事务管理器-->
    <bean id="transactionManager" class="com.hua.utils.TransactionManager">
        <property name="ConnectionUtils" ref="connectionUtils"/>
    </bean>

    <!--代理对象⼯⼚-->
    <bean id="proxyFactory" class="com.hua.factory.ProxyFactory">
        <property name="TransactionManager" ref="transactionManager"/>
    </bean>
</beans>

改造后

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
">
    <!--开启注解扫描,base-package指定扫描的包路径-->
    <context:component-scan base-package="com.hua"/>

    <!--引入外部资源文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--第三方jar中的bean定义在xml中-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
</beans>

新增的约束头
image.png
jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bank
jdbc.username=root
jdbc.password=muZI5945@

4 tomcat插件启动测试

image.png
http://localhost:8080/
image.png
测试成功。

二、使用AOP

1 导入AOP相关依赖

<!--spring aop的jar包支持-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>5.1.12.RELEASE</version>
</dependency>

<!--第三方的aop框架aspectj的jar-->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.8.13</version>
</dependency>

2 创建切面类LogUtils

package com.hua.utils;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class LogUtils {


    @Pointcut("execution(* com.hua.service.impl.AccountServiceImpl.*(..))")
    public void pt1(){

    }


    /**
     * 业务逻辑开始之前执行
     * 切入点为方法名
     */
    @Before("pt1()")
    public void beforeMethod(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            System.out.println(arg);
        }
        System.out.println("业务逻辑开始执行之前执行.......");
    }


    /**
     * 业务逻辑结束时执行(无论异常与否)
     */
    @After("pt1()")
    public void afterMethod() {
        System.out.println("业务逻辑结束时执行,无论异常与否都执行.......");
    }


    /**
     * 异常时时执行
     */
    @AfterThrowing("pt1()")
    public void exceptionMethod() {
        System.out.println("异常时执行.......");
    }


    /**
     * 业务逻辑正常时执行
     * retVal是获取返回值
     */
    @AfterReturning(value = "pt1()",returning = "retVal")
    public void successMethod(Object retVal) {
        System.out.println("业务逻辑正常时执行.......");
    }


    /**
     * 环绕通知
     *
     */
    /*@Around("pt1()")*/
    public Object arroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知中的beforemethod....");

        Object result = null;
        try{
            // 控制原有业务逻辑是否执行
            // result = proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        }catch(Exception e) {
            System.out.println("环绕通知中的exceptionmethod....");
        }finally {
            System.out.println("环绕通知中的after method....");
        }

        return result;
    }

}

3 添加配置

applicationContext.xml中增加AOP的约束头

<!--
    Spring基于XML的AOP配置前期准备:  在spring的配置⽂件中加⼊aop的约束

    xmlns:aop="http://www.springframework.org/schema/aop" 
    http://www.springframework.org/schema/aop
    https://www.springframework.org/schema/aop/spring-aop.xsd

Spring基于XML的AOP配置步骤:
第⼀步:把通知Bean交给Spring管理    
第⼆步:使⽤aop:config开始aop的配置
第三步:使⽤aop:aspect配置切⾯
第四步:使⽤对应的标签配置通知的类型

⼊⻔案例采⽤前置通知,标签为aop:before
-->

具体配置开启注解驱动

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:aop="http://www.springframework.org/schema/aop"
     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/aop
      http://www.springframework.org/schema/beans/spring-aop.xsd
">

     <!--开启aop注解驱动
     proxy-target-class:true强制使用cglib
    -->
    <aop:aspectj-autoproxy/>
</beans>

4 测试

/**
 * 测试xml-anno aop
 */
@Test
public void testXmlAnnoAop() throws Exception {
    ClassPathXmlApplicationContext applicationContext =
            new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    AccountService accountService = applicationContext.getBean(AccountService.class);
    accountService.transfer("6029621011000","6029621011001",100);
}