Spring AOP。从 JoinPoint 获取 bean 名称

Spring AOP. Getting the bean name from the JoinPoint

我有一个应用程序(Spring 4 MVC+Hibernate 4+MySQL+使用注释的 Maven 集成示例),使用基于注释的配置将 Spring 与 Hibernate 集成。如果可能的话,我想从 JoinPoint 获取 bean 名称....

@Aspect
public class TDKAspectLogger {

    private Logger logger = Logger.getLogger(getClass());

    @Before(“execution(void set*(*))”)
    public void logInfo(JoinPoint point) {
          logger.info(“changing bean -> ” );
    } 
}

你可以使用这个:

Stream.of(joinPoint.getTarget().getClass().getAnnotationsByType(Service.class))
      .forEach(q -> logger.info(q.value()));

获取由 @Service 注释声明的 bean。

然而,并不是所有的bean都是这样创建的。有些是由 @Bean 注释方法创建的,有些甚至可以手动添加到上下文中。所以,如果你用 @Component@Service@Qualifier 等注释你的 bean 类 并使用 @ComponentScan 你可能会得到你想要的。您只需要记住,它不是检索上下文中当前可用的所有 bean 的通用方法(它不适用于没有任何 annotations/metadata 的 类)。