Jersy2注入了slf4j Logger

时间:2016-09-07 09:42:50

标签: dependency-injection jersey-2.0 hk2

我试图理解Jersey 2开发和上下文依赖注入。

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

我的资源类是:

@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作为参数,以便在我想要的每个资源中注入正确初始化的Logger?

由于

1 个答案:

答案 0 :(得分:2)

您正在寻找的是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
    }

}