【问题标题】:How to AOP aspectj in OSGi with Apache Felix如何使用 Apache Felix 在 OSGi 中 AOP aspectj
【发布时间】:2016-10-13 16:03:04
【问题描述】:

我目前正在从事一个 OSGi 项目。 没有很多 AOP 与 OSGi 结合的经验,我想知道如何在 OSGi 环境中最好地做 AOP? 我们已经实现了 AOP 场景来创建一个控制台来拦截对包的调用,以便存储该包启动的每个任务的经过时间。 今天,这个方面已经使用 aspectj 提供的 LoadTimeWeaver 部署在一个 jboss 容器上(向 jboss 启动脚本添加一个代理,以便检测容器中的 jar -javaagent:%APP_HOME%\application\lib\aspectjweaver-1.6。 11.jar)。 我已经阅读了一些关于这个问题的文章,但没有找到适合我的解决方案。例如,AspectJ 有一个 Equinox Incubator 项目。但由于我使用的是 Apache Felix 和 Bnd(tools),所以我想避免使用 Equinox 中的某些东西。编织过程的一个要求是它也应该在加载时(用于 aspectj 的包,用于在另一个包中检测方法)。 有人可以分享使用 AOP aspectj 和 OSGI Felix 的这种用例的经验吗?

【问题讨论】:

  • 编织在 OSGi 中是标准化的,因此您可以将其作为捆绑包进行。
  • 您能添加更多信息、链接等吗?在解释的案例中,我们需要创建一个 bundle_A,它必须具有 bundle_B 中存在的方法的切入点。在 bundle_A 的方面类中使用 \@Before 和 \@After 注释,我们可以执行一些操作的日志记录。您能否更好地解释 osgi env 中的解决方案?我见过 WeavingHook,但它并不是很简单,因为 AspectJ 加载时间编织。

标签: osgi aop spring-aop apache-felix


【解决方案1】:

这是一个最小的工作示例 felix aspectj setup

基本模式是:

  1. 在激活时注册编织钩子

    public class Activator implements BundleActivator {
       public void start(BundleContext context) throws Exception {
           AspectWeaver weaver = new AspectWeaver();
           servList.add(context.registerService(WeavingHook.class, weaver, null));
       }
    }
    
  2. 注入编织定义上下文:

    public class AspectContext extends DefaultWeavingContext {
        @Override
        public List<Definition> getDefinitions(final ClassLoader loader, final WeavingAdaptor adaptor) {
            if (definitionList == null) {
                definitionList = AspectSupport.definitionList(loader, rootConfig);
            }
            return definitionList;
        }
    }
    
  3. 提供编织钩子实现

    public class AspectWeaver implements WeavingHook {
      @Override
      public void weave(WovenClass woven) {
          String name = woven.getClassName();
          BundleWiring wiring = woven.getBundleWiring();
          ClassLoaderWeavingAdaptor adaptor = ensureAdaptor(wiring);
          final byte[] source = woven.getBytes();
          final byte[] target;
          // aspectj is single-threaded
          synchronized (adaptor) {
              target = adaptor.weaveClass(name, source);
          }
          woven.setBytes(target);
     }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2010-12-25
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    相关资源
    最近更新 更多