Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a typed map of beans based on a typesafe qualifier in Spring?

See the example below, I'm trying to get a Map of my TypedService beans but I would prefer if the keys were the Type enum values specified in the TypeSafeQualifier instead of the unsafe String "serviceName".

package org.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.Map;

import static org.test.Application.Type.ONE;
import static org.test.Application.Type.TWO;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@SpringBootApplication
public class Application {
  @Autowired
  Map<String, TypedService> works;

  @Autowired
  Map<Type, TypedService> fails;

  public static void main(String [] args) {
    SpringApplication.run(Application.class, args);
  }

  public enum Type {
    ONE,
    TWO
  }

  @Target({TYPE, METHOD, FIELD, CONSTRUCTOR})
  @Retention(RUNTIME)
  @Qualifier
  public @interface TypeSafeQualifier {
    Type value();
  }

  public interface TypedService {
    void startSignup();
    void activate();
  }

  @Service
  @TypeSafeQualifier(ONE)
  public class TypeOneService implements TypedService {

    @Override
    public void startSignup() {
    }

    @Override
    public void activate() {
    }
  }

  @Service
  @TypeSafeQualifier(TWO)
  public class TypeTwoService implements TypedService {

    @Override
    public void startSignup() {
    }

    @Override
    public void activate() {
    }
  }
}

SpringBoot version: springBootVersion=1.5.3.RELEASE

like image 512
Costel Radulescu Avatar asked Aug 24 '17 15:08

Costel Radulescu


People also ask

How do you auto inject into a field a spring bean by its name?

By using both the @Autowired and the @Qualifier spring annotations. D. By using the @Autowired annotation and naming the field with the bean name.

How do you inject a map in spring boot?

3. How to Inject a Map From a YAML File. Spring Boot has taken data externalization to the next level by providing a handy annotation called @ConfigurationProperties. This annotation is introduced to easily inject external properties from configuration files directly into Java objects.

What annotation can you use to inject a spring bean?

The @ComponentScan annotation is used to find beans and the corresponding injected with @Autowired annotation. If you followed the Spring Boot typical layout, no need to specify any arguments for @ComponentScan annotation. All component class files are automatically registered with Spring Beans.


1 Answers

Spring offers a special approach to handle this type of injection: AutowireCandidateResolver.

In your case the code might be:

package org.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.LinkedHashMap;
import java.util.Map;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@SpringBootApplication
public class Application {

  @Autowired
  Map<String, TypedService> works;

  @Autowired
  Map<Type, TypedService> fails;

  @PostConstruct
  private void init() {
    System.out.println(fails);
  }

  public static void main(String[] args) {
    final SpringApplication application = new SpringApplication(Application.class);
    application.addInitializers(context -> {
      context.addBeanFactoryPostProcessor(beanFactory -> {
        final DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory;
        dlbf.setAutowireCandidateResolver(new MyAutowireCandidateResolver(dlbf));
      });
    });
    application.run(args);
  }

  @QualifierValue(TypeSafeQualifier.class)
  public enum Type {
    ONE,
    TWO
  }

  @Target({TYPE, METHOD, FIELD, CONSTRUCTOR})
  @Retention(RUNTIME)
  @Qualifier
  public @interface TypeSafeQualifier {
    Type value();
  }

  public interface TypedService {
    void startSignup();
    void activate();
  }

  @Service
  @TypeSafeQualifier(Type.ONE)
  public class TypeOneService implements TypedService {

    @Override
    public void startSignup() {
    }

    @Override
    public void activate() {
    }
  }

  @Target({TYPE})
  @Retention(RUNTIME)
  public @interface QualifierValue {
    Class<? extends Annotation> value();
  }

  @Service
  @TypeSafeQualifier(Type.TWO)
  public class TypeTwoService implements TypedService {

    @Override
    public void startSignup() {
    }

    @Override
    public void activate() {
    }
  }

  private static class MyAutowireCandidateResolver extends ContextAnnotationAutowireCandidateResolver {

    private final DefaultListableBeanFactory beanFactory;

    private MyAutowireCandidateResolver(DefaultListableBeanFactory beanFactory) {
      this.beanFactory = beanFactory;
    }

    @Override
    public Object getSuggestedValue(DependencyDescriptor descriptor) {
      final Object result = super.getSuggestedValue(descriptor);
      if (result != null) {
        return result;
      }

      if (descriptor.getDependencyType() != Map.class) {
        return null;
      }

      final ResolvableType dependencyGenericType = descriptor.getResolvableType().asMap();
      final ResolvableType[] typeParams = dependencyGenericType.getGenerics();

      final QualifierValue qualifierValue = typeParams[0].getRawClass().getAnnotation(QualifierValue.class);
      if (qualifierValue == null) {
        return null;
      }

      final String[] candidateBeanNames = beanFactory.getBeanNamesForType(typeParams[1]);
      final LinkedHashMap<Object, Object> injectedMap = new LinkedHashMap<>(candidateBeanNames.length);

      for (final String candidateBeanName : candidateBeanNames) {
        final Annotation annotation = beanFactory.findAnnotationOnBean(candidateBeanName, qualifierValue.value());

        if (annotation == null) {
          continue;
        }

        final Map<String, Object> annotationAttributes = AnnotationUtils.getAnnotationAttributes(annotation, false);
        final Object value = annotationAttributes.get("value");

        if (value == null || value.getClass() != typeParams[0].getRawClass()) {
          continue;
        }

        injectedMap.put(value, beanFactory.getBean(candidateBeanName));
      }

      return injectedMap;
    }
  }
}

First of all, we add TypeQualifierValue annotation to make Spring know about a qualifier with values of the given type.

The second is to customize the SpringApplication in the main method: we use BeanFactoryPostProcessor to set a custom AutowireCandidateResolver.

And the final step: we write MyAutowireCandidateResolver extending ContextAnnotationAutowireCandidateResolver (delegation instead of inheritance is applicable to, it's even a little bit better since one day Spring can migrate to `YetAnotherAutowireCandidateResolver' by default).

The crucial part here is the overridden getSuggestedValue method: here we can customize the injection logic considering the generic types of the dependency (field, method parameter) and by applying some getBean...-like methods from the BeanFactory with some magic of Spring AnnotationUtils class.

like image 158
Dmitry Ovchinnikov Avatar answered Oct 02 '22 16:10

Dmitry Ovchinnikov