Spring annotation 实现AOP逻辑

来源:互联网 发布:centos snmp 版本 编辑:程序博客网 时间:2024/05/14 08:01

用annotation实现Spring 的aop 逻辑,很简单,但做的还不太细致。

1.beans.xml中添加xsd文件:spring-aop.xsd,<aop:aspectj-autoproxy>。此时可以用了

2.用@Aspect 注解这个类,表明此类是个切面逻辑,可以切到其他类中

3.建立处理方法:@before("execution (public * com.gao..*.save(..) )")

4.用@Component管理拦截器类。

 1)使用之后的beans.xml文件:

<?xmlversion="1.0" encoding="UTF-8"?>

<beansxmlns="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-2.5.xsd

           http://www.springframework.org/schema/context

           http://www.springframework.org/schema/context/spring-context-2.5.xsd

          http://www.springframework.org/schema/aop

          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<context:annotation-config/><!--这个是使用标注的必备的东西,有了它就可以让你的BEANS.XML很清净 -->

<context:component-scanbase-package="com.gao" />

<aop:aspectj-autoproxy/>

</beans> 

2)aspect 标注的类的状态

@Aspect//表明是标注类

@Component

public classLogInterceptor2 {

@Before("execution (public *com.gao..*.save(..))")//before逻辑

publicvoid before(){

System.out.println("methodbefore!");

}

@After("execution (public *com.gao..*.save(..))")//after逻辑

publicvoid after(){

System.out.println("methodafter!");

}}

3)测试类

@Test

public voidtestSave() {

ClassPathXmlApplicationContextac = new ClassPathXmlApplicationContext("beans.xml");

UserServiceuserService = (UserService) ac.getBean("userService");

userService.save(newUser("gao","wenjian"));//这样就可以直接调用aspect类,save方法没做任何修改的类,但是可以加上aspect的切面方法,是注解起了作用的原因。所以啊,注解很好用,很方便!!这样的话,把用注解进行ID的实现也写下~~

ac.destroy();}

结果出来2遍“method before”跟“method after”,有待解决这个问题~~

Annotiaiton 实现spring的注入依赖。

1)注入资源类

@Component("userDAO")

Public class UserDAOImplimplements userDAO{}

2)待被注入的服务类

@Component("userService")

Publicclass UserServie{

@Resouce(name="userDAO")

Publicvoid setUserDAO(UserDAO userDAO){}

}

3)测试类同上;

这样就实现了userDAO对userService 的自动注入,原因就在@Component("userDAO")与Resource(name="userDAO")这上~~

原创粉丝点击