在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实现对方法的增强和控制。在实际应用中,可以根据具体需求定义不同的切面类和切入点表达式,实现更复杂的业务逻辑控制。