【发布时间】:2020-07-02 10:48:55
【问题描述】:
我一直在使用 Aspect 来记录日志。现在我可以使用之前和之后的建议。但是是否可以在执行某些业务逻辑之后调用通知。这是我当前的代码,我想用建议替换我的代码。该怎么做?
@ComponentScan
@EnableCaching
@EnableAutoConfiguration(exclude = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class})
public class Application {
private final Logger log = LoggerFactory.getLogger(Application.class);
@Inject
private Environment env;
@Inject
private AppConfig appConfig;
public void myBusinessLogicMethod(){
if (myVariable == 0) {
log.info("No Spring profile configured, running with default configuration");
//rest of the business logic here
} else {
log.info("Running with number profile(s) : {}",myVariable);
// //rest of the business logic here
}
我的方面类
@Aspect
@Order(0)
public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Inject
private HttpServletRequest request;
@Inject
private HttpServletResponse response;
@Inject
private Environment env;
@Pointcut("(within(com.repository.*) || within(com.service.*) || "
+ "within(com.web.rest.*)) && "
+ "!@annotation(com.aop.logging.NoLogging)")
public void loggingPoincut() {
}
@Before("within(com.web.rest.*) && "
+ "!@annotation(com.aop.logging.NoLogging)")
public void beforeRest(JoinPoint point) throws UnknownHostException {
String ipAddress = getIpAddress();
if (log.isDebugEnabled()) {
log.debug(">>>>>> From IP {}", isIpAvailble(ipAddress));
log.debug("Enter: {}.{}() with argument[s] = {}", point.getSignature().getDeclaringTypeName(),
point.getSignature().getName(), Arrays.toString(point.getArgs()));
}
}
@After("within(com.web.rest.*) && "
+ "!@annotation(com.aop.logging.NoLogging)")
public void afterRest(JoinPoint point) throws UnknownHostException {
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}()", point.getSignature().getDeclaringTypeName(), point.getSignature()
.getName());
log.debug("<<<<<< Rest Call Finished {} ", response.getStatus());
}
}
}
如何在我的方面类中用建议替换紧密耦合的日志。
【问题讨论】:
-
你使用的是 Spring AOP 还是 AspectJ?
-
@IgorKonoplyanko AspectJ。对不起,我会正确标记:)
-
好吧,现在你标记了两者,所以更不清楚。为了帮助你,我需要看看你用cmets替换了什么。然后我可以建议如何重构现有代码以允许日志记录方面完成其工作。
-
@kriegaex 已更正,
-
是的,但是我请求的附加代码在哪里?很遗憾,我无法读懂你的想法。
标签: java spring aspectj spring-aop