这是我的代码,这只显示了在intellij INFO中执行方法时的日志:发表评论:Demo评论。还添加了依赖项,但我仍然看不到什么错误。
package com.alpha;
import com.alpha.exampleApp.Comment;
import com.alpha.servoces.CommentServoce;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(ComponentConfig.class);
var comment = new Comment();
comment.setAuthor("Laurentiu");
comment.setText("Demo comment");
var commentServoce = context.getBean(CommentServoce.class);
commentServoce.publishComment(comment);
}
}
这是aspect class->
package com.alpha;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import java.util.Arrays;
import java.util.logging.Logger;
@Aspect
public class LogAspect {
private Logger logger = Logger.getLogger(LogAspect.class.getName());
@Around("execution(* com.alpha.servoces.*.*(..))")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
Object[] arguments = joinPoint.getArgs();
logger.info("Method " + methodName +
" with parameters " + Arrays.asList(arguments) +
" will execute");
Object returnedByMethod = joinPoint.proceed();
logger.info("Method executed and returned " + returnedByMethod);
return returnedByMethod;
}
}
这是我的配置类->
package com.alpha;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.alpha.servoces")
public class ComponentConfig {
@Bean
public LogAspect loggingAspect(){
LogAspect logAspect = new LogAspect();
return logAspect;
}
}
这是我想要的方法被拦截的类->
package com.alpha.servoces;
import com.alpha.exampleApp.Comment;
import org.springframework.stereotype.Service;
import java.util.logging.Logger;
@Service
public class CommentServoce {
private Logger logger = Logger.getLogger(CommentServoce.class.getName());
public String publishComment(Comment comment) {
logger.info("Publishing comment: " + comment.getText());
return "SUCCESS";
}
}
我想通过spring中的方面拦截方法来查看日志,但我看不到日志
1条答案
按热度按时间91zkwejq1#
只需用
@EnableAspectJAutoProxy
注解ComponentConfig
类,拦截就可以工作了