Jersy2 注入 slf4j 记录器

Jersy2 inject slf4j Logger

我正在尝试了解 Jersey 2 开发和上下文依赖注入。

我不明白如何将构造函数中需要初始化参数的对象注入到资源中。 例如:我想@Inject slf4j Logger,使用 LoggerFactory 构建。

我的资源 class 是:

@Path("/myresource")
public class MyResource {
    @Inject
    private Logger log;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Answer status() {
        log.info("STATUS");
        return new Answer(200, "Server up and running @ "+ ZonedDateTime.now());
    }
}

我的资源配置是:

public class MyAppextends ResourceConfig {
    public MyApp() {
        register(new MyBinder());
        packages(true, "my.packages");
    }
}

public class MyBinder extends AbstractBinder {

    @Override
    protected void configure() {
        bindFactory(MyLoggerFactory.class).to(org.slf4j.Logger.class);
    }
}

最后,工厂是:

public class MyLoggerFactory implements Factory<Logger> {

    @Override
    public Logger provide() {
        return LoggerFactory.getLogger(TYPE_FOR_LOGGING.class);
    }

    @Override
    public void dispose(Logger logger) {

    }
}

如何将 TYPE_FOR_LOGGING 指定为参数,以便在我想要的每个资源中注入正确初始化的记录器?

谢谢

您要找的是 InstantiationService。你可以将它注入到工厂中,以找出谁在调用提供方法内部的工厂。

下面是来自 hk2 测试的代码示例,说明了 InstantiationService 的用法。

@Singleton
public class CorrelationFactory implements Factory<PerLookupServiceWithName> {
    private final static PerLookupServiceWithName NULL_SERVICE = new PerLookupServiceWithName() {

        @Override
        public String getName() {
            return null;
        }

    };

    @Inject
    private InstantiationService instantiationService;

    /* (non-Javadoc)
     * @see org.glassfish.hk2.api.Factory#provide()
     */
    @Override @PerLookup
    public PerLookupServiceWithName provide() {
        InstantiationData data = instantiationService.getInstantiationData();
        if (data == null) {
            return NULL_SERVICE;
        }

        Injectee parent = data.getParentInjectee();

        if (parent == null) {
            return NULL_SERVICE;
        }

        Class<?> parentClass = parent.getInjecteeClass();
        if (parentClass == null) {
            return NULL_SERVICE;
        }

        Correlator correlator = parentClass.getAnnotation(Correlator.class);
        if (correlator == null) {
            return NULL_SERVICE;
        }

        final String fName = correlator.value();

        return new PerLookupServiceWithName() {

            @Override
            public String getName() {
                return fName;
            }

        };
    }

    /* (non-Javadoc)
     * @see org.glassfish.hk2.api.Factory#dispose(java.lang.Object)
     */
    @Override
    public void dispose(PerLookupServiceWithName instance) {
        // DO nothing
    }

}