I am trying to Practice Spring AOP. The Problem is, My program is not what I expect.
It should Look something like this when Aspect works.
Код: Выделить всё
Sep 27, 2020 1:11:11 PM aspects.LoggingAspect log
INFO: Method will execute
Sep 27, 2020 1:11:11 PM com.cms.services.CommentService publishComment
INFO: Publishing comment:Demo comment
Sep 27, 2020 1:11:11 PM aspects.LoggingAspect log
INFO: Method executed
Код: Выделить всё
com.cms.services.CommentService publishComment
INFO: Publishing Comment: Demo Comment
and also uses CommentService.java.
CommentService.java is nothing but of printing one lined log.
It is placed under services package.
Then there is LoggingAspect.java For Aspect Programming.
Finally, CommentConfig.java is for configuring EnableAspectJAutoProxy and registering Beans for Aspect class.
Here is my code.
Main.java
Код: Выделить всё
public class Main {
public static void main(String[] args) {
var c = new AnnotationConfigApplicationContext(CommentConfig.class);
var service = c.getBean(CommentService.class);
Comment comment = new Comment();
comment.setText("Demo Comment");
comment.setAuthor("Natasha");
service.publishComment(comment);
}
}
Код: Выделить всё
@Service
public class CommentService {
private Logger logger = Logger.getLogger(CommentService.class.getName());
public void publishComment(Comment comment) {
logger.info("Publishing Comment: " + comment.getText());
}
}
Код: Выделить всё
@Aspect
@Component
public class LoggingAspect {
private Logger logger = Logger.getLogger(LoggingAspect.class.getName());
@Around("execution(* services.*.*(..))")
public void log(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("method will execute");
logger.info("Method will execute");
joinPoint.proceed();
logger.info("Method has executed");
System.out.println("method has executed");
}
}
Код: Выделить всё
@Configuration
@ComponentScan(basePackages = {"com.cms"})
@EnableAspectJAutoProxy
public class CommentConfig {
@Bean
public LoggingAspect aspect() {
return new LoggingAspect();
}
}
Код: Выделить всё
17
17
UTF-8
org.springframework
spring-context
5.3.23
org.springframework
spring-aspects
5.3.23
org.springframework
spring-aop
5.3.24
Источник: https://stackoverflow.com/questions/781 ... -triggered