springAOP的注解版

来源:互联网 发布:淘宝宝贝卖点大全 编辑:程序博客网 时间:2024/06/06 03:53

还是之前事务的例子


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的beanpublic 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


单元测试


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

测试结果


beginTransactionsavePersoncommit








0 0
原创粉丝点击