Spring 带给我们的另一个好处就是让我们可以“专心做事”,下面我们来看下面一个例子:
01
<b>
public
void
doSameSomesing(
int
age,String name){
03
log.info(
" 调用 doSameSomesing 方法,参数是: "
+agfe+” ”+name);
06
throws
new
IllegalArgumentException(
"age 应该大于 0"
);
08
if
(name==
null
|| name.trim().equals(
""
)){
09
throws
new
IllegalArgumentException(
"name 不能为空 "
);
13
service.save(age,name);
大家想一下我们构建系统的主要目的是业务处理,但是我们在完成上面业务前需要解决如日志记录,参数验证等如此多方面的事情,这样的话留给我们考虑业务的时间就少了,使我们的业务代码质量得不到很好的保证,而这些方面又是不可缺少的我们不能不管,那么怎么办呢,我们能不能集中对这些方面进行一个统一的管理 ,当然可以,这就是 spring aop 要解决的问题。下面我们来看一个简单的例子,通过 spring aop 来集中解决日志方面的事情。
下面我们按照下面几个步骤去做:
1、 定义并实现对日志方面的处理。
01
<b>
package
com.springaop.aop;
02
import
java.lang.reflect.Method;
03
import
java.util.Arrays;
04
import
java.util.Date;
05
import
org.springframework.aop.MethodBeforeAdvice;
06
public
class
LogAdvice
implements
MethodBeforeAdvice{
07
public
void
before(Method method, Object[] args, Object o)
09
System. out .println(
" 系统日志: "
+(
new
Date())+
":"
+
" 调用了 "
+method.getName()+
" : 使用了参数 "
+(Arrays.toString (args)));
( 注意这里我们要实现 MethodBeforeAdvice 接口 指的是在方法执行前织入执行,类似还有 AfterReturningAdvice )
2、 定义业务代码
2.1 业务接口
01
package
com.springaop.service;
02
public
interface
IAopMethod {
03
public
void
doSomesing(String name);
06
package
com.springaop.service.impl;
07
import
com.springaop.service.IAopMethod;
08
public
class
AopMethodimpl
implements
IAopMethod {
09
public
void
doSomesing(String name) {
10
System. out .println(
"name:"
+name);
3. 配置 applicationContext.xml.
02
<
bean
name
=
"mylogadvice"
class
=
"com.springaop.aop.LogAdvice"
></
bean
>
04
<
bean
name
=
"aopmethodtarget"
class
=
"com.springaop.service.impl.AopMethodimpl"
></
bean
>
06
<
bean
name
=
"aopmethod"
class
=
"org.springframework.aop.framework.ProxyFactoryBean "
>
07
<
property
name
=
"interceptorNames"
>
09
<
value
> mylogadvice </
value
>
13
<
property
name
=
"target"
ref
=
"aopmethodtarget"
></
property
>
4. 测试类
01
package
com.springaop.service.impl;
02
import
org.springframework.context.ApplicationContext;
03
import
org.springframework.context.support.ClassPathXmlApplicationContext;
04
import
com.springaop.service.IAopMethod;
06
public
static
void
main(String[] args) {
07
ApplicationContext context=
new
ClassPathXmlApplicationContext(
"applicationContext.xml"
);
08
IAopMethod method=(IAopMethod)context.getBean(
"aopmethod"
);
09
method.doSomesing(
" zhangsan "
);
运行结果是:
系统日志: Fri Sep 24 12:45:24 CST 2010: 调用了 doSomesing : 使用了参数 [zhangsan]
hello: zhangsan
此为为转发