spring(5)-(17)使用注解开发AOP

2018-09-29  本文已影响6人  小白201808

主要工作就是贴注解啦~~~

ackage com.keen.proxy.tx;

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 TransactionManager {
    // xml:<aop:pointcut id="txPoint" expression="execution(*
    // com.keen.proxy.service.*Service.*(..))" />
    @Pointcut("execution(* com.keen.proxy.service.*Service.*(..))")
    public void txPoint() {

    }

    //@Before("txPoint()")
    public void begin() {
        System.out.println("开启事务");
    }

    //@AfterReturning("txPoint()")
    public void commit() {
        System.out.println("提交事务");
    }

    //@AfterThrowing(value = "txPoint()", throwing = "ex")
    public void rollback(Throwable ex) {
        System.out.println("回滚事务 异常信息:" + ex.getMessage());
    }

    //@After("txPoint()")
    public void close() {
        System.out.println("释放资源");

    }

    // 环绕增强(返回一个object类型)
    // ProceedingJoinPoint:Joinpoint子类,只能用于环绕增强,可以处理被增强的方法
    @Around("txPoint()")
    public Object aroundMethod(ProceedingJoinPoint pjp) {
        Object ret = null;
        System.out.println("开启事务");
        try {
            // System.out.println("记录日志,其实真正调用应该是调用日志");
            // System.out.println("...执行真实对象的方法...");
            ret = pjp.proceed();// 执行真实对象的方法
            System.out.println("提交事务");

        } catch (Throwable e) {
            System.out.println("回滚事务,异常信息:" + e.getMessage());

        } finally {
            System.out.println("释放资源");

        }
        return ret;

    }
}

(2)配置文件

...
<!-- di注解解析器 -->
 <context:annotation-config/>

<!--IOC注解解析器  -->
 <context:component-scan base-package="com.keen.proxy"/>
<!-- AOP注解解析器 -->
<aop:aspectj-autoproxy/>
....

分别在其他两个bean中贴注解
(1)EmployeeDAOimpl

@Repository
public class EmployeeDAOimpl implements EmployeeDAO{...}

(2)IEmployeeServiceImpl

@Service
public class IEmployeeServiceImpl  implements IEmployeeService{...}

3.测试类

...//引入的一些包
@SpringJUnitConfig
public class AutoTest {
    @Autowired 
    private IEmployeeService service;
    
    
    @Test
    void testSave() throws Exception {
        
         System.out.println(service.getClass());
         service.save(new Employee());
    }
    @Test
    void testUpdate() throws Exception {
        
         service.update(new Employee());
        
    }
    
}

上一篇下一篇

猜你喜欢

热点阅读