在SpringBoot中使用AOP(面向切面編程),可以通過以下步驟實現:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.demo.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Method executed: " + joinPoint.getSignature().getName());
}
@After("execution(* com.example.demo.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("Method execution completed: " + joinPoint.getSignature().getName());
}
}
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@Service
public class UserService {
public void addUser(String username) {
System.out.println("User added: " + username);
}
public void deleteUser(String username) {
System.out.println("User deleted: " + username);
}
}
通過以上步驟,就可以在SpringBoot應用程序中使用AOP實現對方法的增強和控制。在實際應用中,可以根據具體需求定義不同的切面類和切入點表達式,實現更復雜的業務邏輯控制。