有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在激活器中获取IEclipseContext

我在Eclipse4RCP应用程序中遇到了一个问题。我需要记录一些事件。我需要以某种方式获得记录器的参考。我知道,如何使用IEclipseContext实现这一点,但我还没有找到,如何在没有依赖注入的情况下获得IEclipseContext,我无法在激活器中使用依赖注入。你知道怎么解决这个问题吗

非常感谢


共 (2) 个答案

  1. # 1 楼答案

    遗憾的是,如果不使用注入,就无法获得IEclipseContext。 对How to use eclipse 4 DI in classes that are not attached to the application model的答复中写道:

    The problem is, however, that the IEclipseContext already needs to be injected into a class that can access the object that needs injection.

    尽管如此,我已经解决了日志记录的问题,我认为这个原则基本上是有效的。总会有一些服务提供你需要的东西。如果不能使用依赖项注入,则必须以某种方式(通常是互联网和实验)获得合适的服务类名。如果您已经获得了服务类名,那么可以从bundle上下文中获取实例引用。幸运的是,bundle上下文可以在不使用注入的情况下访问

    回到我们的日志问题。正在搜索的类是^{

    public class Activator implements BundleActivator {
        ...
        private static BundleContext context;
        ...
    
        public static BundleContext getContext() {
            return context;
        }
        ...
        public void start(BundleContext bundleContext) throws Exception {
            ServiceReference<?> logser = bundleContext.getServiceReference(LogService.class);
            LogService ls = (LogService)bundleContext.getService(logser);
            //print an error to test it (note, that info can be below the threshold)
            ls.log(LogService.LOG_ERROR, "The bundle is starting...");
            Activator.context = bundleContext;
        }
        ...
    }
    

    !ENTRY eu.barbucha.rcp-experiment.kernel 4 0 2013-08-20 07:32:32.347
    !MESSAGE The bundle is starting...
    

    就这些。稍后,如果需要,可以使用Activator.getContext()获取捆绑包上下文

    重要提示:很遗憾,您现在无法降低阈值。JVM参数-Declipse.log.level不会影响OSGI日志服务,您现在只使用OSGI日志。不幸的是,他们(可能暂时)硬编码了日志记录阈值(参见How to log warnings and infos in eclipse 3.7)。我发现他们还没修好。开普勒版本中也没有。但是你可以做出妥协。如果可能的话,你可以这样做

    最终解决方案(在全球范围内捕获异常)

    我扩展了激活器:

    ServiceReference<?> logreser = bundleContext.getServiceReference(LogReaderService.class);
    LogReaderService lrs = (LogReaderService) bundleContext.getService(logreser);   
    lrs.addLogListener(new LogListener() {
        @Override
        public void logged(LogEntry entry) {
            System.err.println("Something was logged: " + entry.getMessage());
        }
    });
    

    当某个地方记录了某个东西时,以Something was logged开头的文本就会出现。但最重要的是,这门课是我的。我能控制它。日志条目还包含级别。我还可以轻松设置阈值。例如在命令行上

  2. # 2 楼答案

    您可以通过调用EclipseContextFactory.getServiceContext(bundleContext)获得一个专门的IEclipseContext,它将允许访问OSGi服务