ssslinppp

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

说明


After增强处理的作用非常类似于异常处理中的finally块的作用,无论如何,他总会在方法执行结束之后被织入,因此特别适应于垃圾回收。

项目结构



程序


@Component("hello")
public class HelloImpl implements Hello
{
    // 定义一个简单方法,模拟应用中的业务逻辑方法
    public void foo()
    {
        System.out.println("执行Hello组件的foo()方法");
    }
    
    // 定义一个addUser()方法,模拟应用中的添加用户的方法
    public int addUser(String name , String pass)
    {
        System.out.println("执行Hello组件的addUser添加用户:" + name);
        if(name.length() < 3 || name.length() > 10)
        {
            throw new IllegalArgumentException("name参数的长度必须大于3,小于10!");
        }
        return 20;
    }
} 

 @Component("world")
public class WorldImpl implements World
{
    // 定义一个简单方法,模拟应用中的业务逻辑方法
    public void bar()
    {
        System.out.println("执行World组件的bar()方法");
    }
}


定义切面


// 定义一个切面
@Aspect
public class ReleaseAspect
{
    // 匹配org.crazyit.app.service包下所有类的、
    // 所有方法的执行作为切入点
    @After("execution(* org.crazyit.app.service.*.*(..))")
    public void release()
    {
        System.out.println("模拟方法结束后的释放资源...");
    }
}  



配置


<?xml version="1.0" encoding="GBK"?>
<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-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
    <!-- 指定自动搜索Bean组件、自动搜索切面类 -->
    <context:component-scan base-package="org.crazyit.app.service
        ,org.crazyit.app.aspect">
        <context:include-filter type="annotation"
            expression="org.aspectj.lang.annotation.Aspect"/>
    </context:component-scan>
    <!-- 启动@AspectJ支持 -->
    <aop:aspectj-autoproxy/>
</beans>  


测试


public class BeanTest
{
    public static void main(String[] args)
    {
        // 创建Spring容器
        ApplicationContext ctx = new
            ClassPathXmlApplicationContext("beans.xml");
        Hello hello = ctx.getBean("hello" , Hello.class);
        hello.foo();
        hello.addUser("孙悟空" , "7788");
        World world = ctx.getBean("world" , World.class);
        world.bar();
    }
} 


链接:
@AfterThrowing增强处理简单示例http://www.cnblogs.com/ssslinppp/p/4633595.html 
《@AfterReturning增强处理简单示例》http://www.cnblogs.com/ssslinppp/p/4633496.html 
《@After后向增强处理简单示例》http://www.cnblogs.com/ssslinppp/p/4633427.html 
《@Before前向增强处理简单示例》 http://www.cnblogs.com/ssslinppp/default.html?page=7 





附件列表

     

    posted on 2015-07-09 15:58  ssslinppp  阅读(1847)  评论(0编辑  收藏  举报