您的位置:首页 > 编程语言 > Java开发

spring AOP @Around @Before @After 区别

2013-07-25 15:23 513 查看
此段小代码演示了springaop中@Around@Before@After三个注解的区别

@Before是在所拦截方法执行之前执行一段逻辑。

@After是在所拦截方法执行之后执行一段逻辑。

@Around是可以同时在所拦截方法的前后执行一段逻辑。


1.[代码][Java]代码

01
package
com.itsoft.action;
02
03
import
org.springframework.context.support.ClassPathXmlApplicationContext;
04
import
org.springframework.stereotype.Controller;
05
06
/**
07
*
08
*
@authorzxf
09
*
演示aop测试类
10
*/
11
@Controller
12
public
class
UserAction
{
13
14
public
void
queryUsers(){
15
16
System.out.println(
"查询所有用户【all
userslist】"
);
17
}
18
19
public
static
void
main(String[]
args){
20
21
ClassPathXmlApplicationContext
ctx=
new
ClassPathXmlApplicationContext(
"application-aop.xml"
);
22
23
UserAction
userAction=(UserAction)ctx.getBean(
"userAction"
);
24
userAction.queryUsers();
25
26
ctx.destroy();
27
}
28
}


2.[代码][Java]代码

01
package
com.itsoft;
02
03
import
org.aspectj.lang.ProceedingJoinPoint;
04
import
org.aspectj.lang.annotation.After;
05
import
org.aspectj.lang.annotation.Around;
06
import
org.aspectj.lang.annotation.Aspect;
07
import
org.aspectj.lang.annotation.Before;
08
import
org.aspectj.lang.annotation.Pointcut;
09
import
org.springframework.stereotype.Component;
10
11
/**
12
*
13
*
@authorAdministrator
14
*
通过aop拦截后执行具体操作
15
*/
16
@Aspect
17
@Component
18
public
class
LogIntercept
{
19
20
@Pointcut
(
"execution(public
*com.itsoft.action..*.*(..))"
)
21
public
void
recordLog(){}
22
23
24
@Before
(
"recordLog()"
)
25
public
void
before()
{
26
this
.printLog(
"已经记录下操作日志@Before
方法执行前"
);
27
}
28
29
@Around
(
"recordLog()"
)
30
public
void
around(ProceedingJoinPoint
pjp)
throws
Throwable{
31
this
.printLog(
"已经记录下操作日志@Around
方法执行前"
);
32
pjp.proceed();
33
this
.printLog(
"已经记录下操作日志@Around
方法执行后"
);
34
}
35
36
37
@After
(
"recordLog()"
)
38
public
void
after()
{
39
this
.printLog(
"已经记录下操作日志@After
方法执行后"
);
40
}
41
42
43
private
void
printLog(String
str){
44
System.out.println(str);
45
}
46
}


3.[代码]演示@Around@Before@After区别

01
<?xml
version=
"1.0"
encoding=
"UTF-8"
?>
02
<beans
xmlns=
"http://www.springframework.org/schema/beans"
03
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
04
xmlns:aop=
"http://www.springframework.org/schema/aop"
05
xmlns:context=
"http://www.springframework.org/schema/context"
06
xsi:schemaLocation="
07
http:
//www.springframework.org/schema/context
08
http:
//www.springframework.org/schema/context/spring-context-3.0.xsd
09
http:
//www.springframework.org/schema/beans
10
http:
//www.springframework.org/schema/beans/spring-beans-3.0.xsd
11
http:
//www.springframework.org/schema/aop
12
http:
//www.springframework.org/schema/aop/spring-aop-3.0.xsd">
13
<context:annotation-config
/>
14
<context:component-scan
base-
package
=
"com.itsoft"
/>
15
<aop:aspectj-autoproxy
/>
16
</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: