已知HelloSpeaker类,定义如下: 请通过Sprintg AOP完成以下步骤: (1)利用XML实现该类的所有以hello开始的方法执行之前,控制台输出提示信息“这是前置通知” (2)利用XML实现该类的所有以hello开始的方法执行之后,控制台输出提示信息“这是后置通知” (3)利用注解完成环绕通知打印出t1方法的执行所花费时间。 (4)利用注解完成环绕通知打印出t2方法的抛出异常的时间和抛出的异常信息。
时间: 2024-01-22 10:17:20 浏览: 28
(1)利用XML实现该类的所有以hello开始的方法执行之前,控制台输出提示信息“这是前置通知”
在XML配置文件中添加如下代码:
```xml
<bean id="helloSpeaker" class="com.example.HelloSpeaker"/>
<aop:config>
<aop:aspect id="myAspect" ref="helloAspect">
<aop:before method="beforeAdvice" pointcut="execution(* com.example.HelloSpeaker.hello*(..))"/>
</aop:aspect>
</aop:config>
<bean id="helloAspect" class="com.example.HelloAspect"/>
```
在HelloAspect类中添加如下代码:
```java
public void beforeAdvice(){
System.out.println("这是前置通知");
}
```
(2)利用XML实现该类的所有以hello开始的方法执行之后,控制台输出提示信息“这是后置通知”
在XML配置文件中添加如下代码:
```xml
<bean id="helloSpeaker" class="com.example.HelloSpeaker"/>
<aop:config>
<aop:aspect id="myAspect" ref="helloAspect">
<aop:after method="afterAdvice" pointcut="execution(* com.example.HelloSpeaker.hello*(..))"/>
</aop:aspect>
</aop:config>
<bean id="helloAspect" class="com.example.HelloAspect"/>
```
在HelloAspect类中添加如下代码:
```java
public void afterAdvice(){
System.out.println("这是后置通知");
}
```
(3)利用注解完成环绕通知打印出t1方法的执行所花费时间。
在HelloSpeaker类的t1方法上添加@Around注解,并在HelloAspect类中添加如下代码:
```java
@Around("execution(* com.example.HelloSpeaker.t1(..))")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = pjp.proceed();
long endTime = System.currentTimeMillis();
System.out.println("t1方法执行所花费时间:" + (endTime - startTime) + "ms");
return result;
}
```
(4)利用注解完成环绕通知打印出t2方法的抛出异常的时间和抛出的异常信息。
在HelloSpeaker类的t2方法上添加@Around注解,并在HelloAspect类中添加如下代码:
```java
@Around("execution(* com.example.HelloSpeaker.t2(..))")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
Object result;
try {
result = pjp.proceed();
} catch (Exception e) {
long exceptionTime = System.currentTimeMillis();
System.out.println("t2方法抛出异常的时间:" + exceptionTime + "ms");
System.out.println("抛出的异常信息:" + e.getMessage());
throw e;
}
long endTime = System.currentTimeMillis();
System.out.println("t2方法执行所花费时间:" + (endTime - startTime) + "ms");
return result;
}
```