Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Custom injection of configuration properties
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.logging.Logger;
import javax.inject.Singleton;
import org.glassfish.hk2.api.Injectee;
import org.glassfish.hk2.api.InjectionResolver;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
* Run this test class like any other JUnit test. It makes use of Jersey Test
* Framework. You will need to following dependency to run it.
* <dependency>
* <groupId>org.glassfish.jersey.test-framework.providers</groupId>
* <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
* <version>${jersey2.version}</version>
* <scope>test</scope>
* </dependency>
public class CustomInjectPropsTest extends JerseyTest {
public static @interface Config {
String value();
private static final String PROP_KEY = "Prop_Key";
private static final String PROP_VALUE = "PropValue";
public static class ConfigInjectionResolver implements InjectionResolver<Config> {
private Configuration configuration;
public Object resolve(Injectee injectee, ServiceHandle<?> handle) {
if (String.class == injectee.getRequiredType()) {
Config annotation = injectee.getParent().getAnnotation(Config.class);
if (annotation != null) {
String prop = annotation.value();
return (String)configuration.getProperty(prop);
return null;
public boolean isConstructorParameterIndicator() { return false; }
public boolean isMethodParameterIndicator() { return false; }
public static class ConfigResource {
private String propValue;
public String getConfigProp() {
return propValue;
public ResourceConfig configure() {
ResourceConfig config = new ResourceConfig(ConfigResource.class);
config.register(new LoggingFilter(Logger.getAnonymousLogger(), true));, PROP_VALUE);
config.register(new AbstractBinder(){
protected void configure() {
.to(new TypeLiteral<InjectionResolver<Config>>(){})
return config;
public void should_return_config_property_value() {
Response response = target("config").request().get();
assertEquals(200, response.getStatus());
assertEquals(PROP_VALUE, response.readEntity(String.class));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment