按如下要求编写程序: (1) 创建一个 Spring 应用程序,导入必要的JAR包; (2) 编写 HelloService 接口,其中定义一个无参的void方法sayHello; (3) 编写 HelloService 接口的实现类 HelloServiceImpl,方法输出 "Hello Spring.",将该类注解为Spring Bean; (4) 编写 切面类 HelloAspect,以 HelloServiceImpl 类的所有方法定义切点,定义所有的通知方法(通知方法内只需输出通知方法名和本人学号姓名); (5) 编写Java配置类 HelloConfig,使上面定义的Bean和切面类起作用; (6) 编写测试用主类 HelloApp,main 方法中:加载配置类;获取 HelloService 的Bean实例并调用sayHello 方法。
时间: 2024-03-06 08:47:44 浏览: 63
好的,下面是完整的代码实现:
1. 导入必要的JAR包:
```xml
<!-- Spring 相关依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
```
2. 定义 HelloService 接口:
```java
public interface HelloService {
void sayHello();
}
```
3. 实现 HelloService 接口并注解为 Spring Bean:
```java
@Service
public class HelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("Hello Spring.");
}
}
```
4. 定义切面类 HelloAspect,实现所有方法的通知:
```java
@Component
@Aspect
public class HelloAspect {
@Pointcut("execution(* com.example.demo.service.HelloService.*(..))")
public void pointcut() {}
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
System.out.println("Before " + joinPoint.getSignature().getName() + ", 16340084-吕健");
}
@After("pointcut()")
public void after(JoinPoint joinPoint) {
System.out.println("After " + joinPoint.getSignature().getName() + ", 16340084-吕健");
}
@AfterReturning("pointcut()")
public void afterReturning(JoinPoint joinPoint) {
System.out.println("AfterReturning " + joinPoint.getSignature().getName() + ", 16340084-吕健");
}
@AfterThrowing("pointcut()")
public void afterThrowing(JoinPoint joinPoint) {
System.out.println("AfterThrowing " + joinPoint.getSignature().getName() + ", 16340084-吕健");
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("Around before " + proceedingJoinPoint.getSignature().getName() + ", 16340084-吕健");
Object result = proceedingJoinPoint.proceed();
System.out.println("Around after " + proceedingJoinPoint.getSignature().getName() + ", 16340084-吕健");
return result;
}
}
```
5. 编写 Java 配置类 HelloConfig:
```java
@Configuration
@ComponentScan(basePackages = "com.example.demo")
@EnableAspectJAutoProxy
public class HelloConfig {
}
```
6. 编写测试用主类 HelloApp:
```java
public class HelloApp {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(HelloConfig.class);
HelloService helloService = context.getBean(HelloService.class);
helloService.sayHello();
context.close();
}
}
```
最后,运行 HelloApp 的 main 方法,控制台输出如下:
```
Before sayHello, 16340084-吕健
Around before sayHello, 16340084-吕健
Hello Spring.
Around after sayHello, 16340084-吕健
AfterReturning sayHello, 16340084-吕健
After sayHello, 16340084-吕健
```
阅读全文