我需要解决这个问题:
在loggeraop类中,使用spring aop,截获对使用logexecution注解注解的公共方法的所有调用,并在logger字段上调用log方法,截获的方法的名称作为数据参数。
import org.aspectj.lang.*;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.*;
import java.lang.annotation.*;
import java.util.*;
@Aspect
@Component
public class LoggerAOP {
@Autowired private Logger logger;
public void loggingAdvice(JoinPoint jp) {
}
public static void main(String[] args) {
AnnotationConfigApplicationContext config = new AnnotationConfigApplicationContext();
config.register(Config.class);
config.refresh();
NameRepository repository = config.getBean(NameRepository.class);
System.out.println(repository.getNames());
}
}
@Component
class NameRepository {
@LogExecution
public List<String> getNames() {
List<String> names = new ArrayList<>();
names.add("John");
names.add("Mary");
return names;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface LogExecution {}
interface Logger {
public void log(String data);
}
@Configuration
@EnableAspectJAutoProxy
@Import({LoggerAOP.class, NameRepository.class})
class Config {
@Bean
public Logger logger() {
return (message) -> System.out.println(message);
}
}
我刚到Spring,所以我还得学点东西。
1条答案
按热度按时间relj7zay1#
与问题共享的代码作为spring应用程序工作,没有任何问题。基于共享的代码,以下方面将建议使用
@LogExecution
Package 内rg.so
以及它的子 Package 。代码使用@Around
建议。参考官方文件
Springaop:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop
关于建议:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-ataspectj建议
写好切入点:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#writing-很好的切入点