springAOP的注解版

还是之前事务的例子


applicationContext.xml的配置文件,注意头的信息


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   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 
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd">
    
    <!-- 这是一个类扫描 -->
  	<context:component-scan base-package="com.mo.transaction"></context:component-scan>
  	
  	<!-- AOP自动创建代理 -->
  	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  	
</beans>


PersonDaoImpl.java

@Repository("personDao")//在spring容器中创建一个id为personDao的bean
public class PersonDaoImpl implements PersonDao {
	public String savePerson() {
		System.out.println("savePerson");
		return "sss";
	}
}


切面:事务


@Component("transaction")
@Aspect//这就是一个切面
public class Transaction {
	
	/**
	 *	 	@Aspect +
	 * 		@Pointcut("execution(* com.mo.transaction.PersonDaoImpl.*(..))") +
	 * 		private void aa(){}
	 * 		==
	 * 		<aop:config>
	 * 			<aop:pointcut
	 * 				expression="execution(* com.mo.transaction.PersonDaoImpl.*(..))"
	 * 				id="aa()">
	 * 		</aop:config>
	 */
	
	
	
	@Pointcut("execution(* com.mo.transaction.PersonDaoImpl.*(..))")
	private void aa(){}//这是一个方法签名
	
	/**
	 * 前置通知
	 * 	在目标方法执行之前执行
	 * 		参数:连接点,可以获取连接点相关的信息
	 */
	@Before("aa()")
	public void beginTransaction(){
		System.out.println("beginTransaction");
	}
	
	/**
	 * 后置通知
	 * 	在目标方法执行之后执行
	 * 		可以获取目标方法的返回值:通过在后置通知中配置的returning="val",在通知这里需要配置参数Object val,用来收集参数
	 * 注意:当调用连接点的方法的时候,抛出了异常,那么后置通知将不再执行
	 */
	@AfterReturning("aa()")
	public void commit(){//这里的参数,val要与spring配置文件中的后置通知中的returning="val" 一致
		System.out.println("commit");
	}
	
}



在这里

@Component是通用的 

@Repository、@Service、@Controller则是细化 


他们的作用都是标志着是spring容器中的一个bean


单元测试


@Test
	public void aopTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
        PersonDao personDao = (PersonDao)context.getBean("personDao");
        personDao.savePerson();
	}

测试结果


beginTransaction
savePerson
commit








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值