SSM[spring] 基于注解的AOP使用

示例代码

[AccountServiceImp]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.gphper.Imp;

import com.gphper.IAccountService;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImp implements IAccountService {
@Override
public void saveAccount() {
System.out.println("保存账号成功");
}

@Override
public void updateAccount(int i) {
System.out.println("更新账号id"+i);
}

@Override
public void deleteAccount() {
System.out.println("删除账号成功");
}
}

[LogUtil]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.gphper.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component("log")
@Aspect
public class LogUtil {

@Pointcut("execution(* *..*.*(..))")
public void ptr1(){};
public void printLog(){
System.out.println("打印日志输出········");
}

@Around("ptr1()")
public Object aroundNotify(ProceedingJoinPoint pjp){

Object valObj = null;
try {
Object[] args = pjp.getArgs();
System.out.println("通知前····");
valObj = pjp.proceed(args);
System.out.println("通知后····");
}catch (Throwable e){

}

return valObj;
}
}

[bean.xml]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="com.gphper"></context:component-scan>

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
[Test.java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.test;

import com.gphper.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApoTest {

public static void main(String[] args) {

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");

IAccountService as = (IAccountService)ac.getBean("accountService");

as.saveAccount();

}


}

Spring中的事务处理