osgi - 如何使用 Apache Felix 在 OSGi 中对切面进行 AOP

标签 osgi aop spring-aop apache-felix

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

最佳答案

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

基本模式是:

  1. 激活时注册编织钩子(Hook)

    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. 注入(inject)编织定义上下文:

    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. 提供编织钩子(Hook)实现

    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);
     }
    

关于osgi - 如何使用 Apache Felix 在 OSGi 中对切面进行 AOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37786309/

相关文章:

java - AspectJ 有什么用?

java - 没有 @EnableAspectJAutoProxy,Spring AOP 能工作吗?

spring - @Tansactional 和 @Aspect 排序

multithreading - Spring-AOP和多线程

file - 无法访问 bundle 资源/文件 (OSGi)

grails - Karaf 4上的Grails3。有人设法做到了吗?

java - Camel Jetty 中的自定义基本身份验证

osgi - FOP/AEM : Deserialization not allowed for class org. apache.fop.fonts.FontCache

java - 使用 around advice 取消方法执行并在方面内手动执行此方法

java - 使用 Spring(AOP?)实现 Java 接口(interface)