获取运行时切面实例

huangapple go评论70阅读模式
英文:

Get instance of aspect at runtime

问题

我正在运行一个使用基于注解的切面来收集统计信息的命令行应用程序。

是否可能检索切面实例以获取统计信息?还是唯一可能的方法是将统计信息保留为static变量,并在所需时获取?

@Aspect
public class StatisticsAspect {

    private static final Logger LOGGER = Logger.getLogger(StatisticsAspect.class);
    private final Statistics statistics;

    public StatisticsAspect() {
        statistics = new Statistics();
    }

    // 一些代码...
}
英文:

I'm running a command line application that uses annotation based aspect to gather statistics.

Is it possible to retrieve aspect instance to fetch the statistics? Or the only possible way is to keep statistics as static variable and get it at desired moment?

@Aspect
public class StatisticsAspect {

    private static final Logger LOGGER = Logger.getLogger(StatisticsAspect.class);
    private final Statistics statistics;

    public StatisticsAspect() {
        statistics = new Statistics();
    }

    // Some code...
}

答案1

得分: 1

AspectJ切面默认为单例模式,即使用静态变量(如果存储与线程相关的信息,可能是静态的ThreadLocal),并且可能提供一个良好的静态获取方法是一个不错的选择。还有其他实例化模型,但对于它们,您需要以不同的方式声明切面,类似于@Aspect("perthis(execution(* ajia.Account.*(..)))")。总之,有以下实例化类型:perthis()pertarget()percflow()percflowbelow()pertypewithin()。如果您的统计信息确实是全局的话,在您的情况下不需要担心这些。

作为替代方案,您还可以将统计信息保留在实例变量中,但如果像在您的情况下是私有的话,您还需要为它提供一个getter方法,类似于public Statistics getStatistics()。在这种情况下,如果您想要访问由AspectJ管理的单例切面实例,您应该使用Aspects.aspectOf(StatisticsAspect.class),详见AspectJ手册。然后您可以像这样访问数据:

Aspects.aspectOf(StatisticsAspect.class).getStatistics();
英文:

AspectJ aspects are by default singletons, i.e. using a static variable (maybe a static ThreadLocal, if you store thread-related information) and maybe providing a nice static getter method is a good option. There are other instantiation models, but for them you need to declare the aspect in a different way, something like @Aspect("perthis(execution(* ajia.Account.*(..)))"). All in all, there are the instantiation types perthis(), pertarget(), percflow(), percflowbelow() and pertypewithin(). It is nothing to worry about in your case if your statistics are really global.

As an alternative, you can also keep the statistics in an instance variable, but if it is private like in your case, you also need to provide a getter method for it, something like public Statistics getStatistics(). In that case, if you want to get access to an AspectJ-managed singleton aspect instance, you ought to use Aspects.aspectOf(StatisticsAspect.class), see also the AspectJ manual. Then you would access the data like this:

<!-- language: java -->

Aspects.aspectOf(StatisticsAspect.class).getStatistics();

huangapple
  • 本文由 发表于 2020年9月24日 21:57:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64048044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定