Core Java. Lecture #13

Dependency Injection. DI containers working principle. Spring Framework (Spring DI, Spring AOP)

Ivan Ponomarev, Synthesized.io/MIPT

Наш пример про доклады и спикеров

objects
wiring

Реальная «слоистая» архитектура серверного приложения

layers
wiring coupling

Попытка №1, наивная. «Пусть объекты сами создают себе то, что им надо»

public class DataSource {
  private ConnectionPool pool = new ConnectionPool(....);
    //взятые откуда-то параметры подключения к БД ^^^^^^
  ...
}

public class SpeakerDao {
  private DataSource ds = new DataSource();
  ...
}

public class TalkDao {
  private DataSource ds = ???
    //нам нужен один ConnectionPool на всех...
    //не получается :-(
  ...
}

Попытка №2. Выложим ссылку на единичный объект в статическое поле

public class ConnectionPool {
  private final static ConnectionPool instance =
                                  new ConnectionPool(...);
  public static ConnectionPool getInstance() {
    return instance;
  }
  //конструктор сделаем приватным, чтобы ни у кого не было соблазна
  //создать объект явно
  private ConnectionPool(...){

  }
}

Попытка №2. (продолжение)

public class DataSource {
  private final static DataSource instance = ...
  public DataSource getInstance() {
    return instance;
  }

  private ConnectionPool pool = ConnectionPool.getInstance();

  private DataSource() {
    ...
  }
}

Мы только что изобрели дизайн-паттерн «Одиночка»!

gof
  • Erich Gamma et al., Design Patterns: Elements of Reusable Object-Oriented Software

  • Книга 1994 года

  • Классическая книга по дизайну ПО…​

  • …​но местами уже устаревшая.

Singleton Pattern

  • Прямое создание невозможно (инксапсулировано в приватном конструкторе).

  • Доступ к единственному экземпляру только через статический метод getInstance() (или final-переменную INSTANCE).

  • Ведёт к проблемам архитектурного плана.

  • В современном программировании вытеснен DI (dependency injection), о котором речь впереди.

Проблемы GoF-cинглетона

How do I automatically test components that are hard-coded to their dependencies through static fields/methods?

  • No way you can do it!

Проблемы GoF-cинглетона

  • Increases coupling

  • Violates the Single Responsibility Principle

  • Unable to test normally

Фабрика

// вынесли весь "wiring" из классов в фабричный метод
public static Controller makeController() {
  DataSource dataSource =
                new DataSource(ConnectionPool.getInstance());
  ConferenceDao conferenceDao = new ConferenceDao(dataSource);
  SpeakerDao speakerDao = new SpeakerDao(dataSource);
  TalkDao talkDao = new TalkDao(dataSource);
  return new Controller(conferenceDao, speakerDao, talkDao);
}

Фабрика

  • We got rid of "wiring" and can create components separately, which allows us to test.

  • However, in the factory method there are many repetitive actions, the factory must "know" about all the components.

  • In general, this process can be automated!

Dependency Injection

di class

Dependency Injection

di seq

DI Frameworks

  • Google Guice

  • JBoss Seam Framework

  • PicoContainer

  • Spring

Let’s build our own homemade DI-framework

  • Example based on Evgeny Borisov’s training "Spring Ripper"

  • Allows you to understand the logic and internals of the Spring Framework

Лектор-робот

robotlecturer
public class RobotLecturer {
    //«магическим» образом пусть тут появится то, что нужно!
    @InjectByType
    private Lecture lecture;
    @InjectByType
    private Speaker speaker;
    @InjectByType
    private SlideShow slideShow;
    ...
}

Режим лектора

//Читать лекции просто
public void lecture() {
    lecture.getSlides().forEach(
        slide -> {
            slideShow.show(slide.getText());
            speaker.speak(slide.getComment());
        }
    );
}

//Main-метод
public static void main(String[] args)
                  throws ReflectiveOperationException {
    RobotLecturer lecturer =
        new ObjectFactory().createObject(RobotLecturer.class);
    lecturer.lecture();
}

Конфигуратор объекта

@RequiredArgsConstructor
public class InjectByTypeAnnotationObjectConfigurator
                             implements ObjectConfigurator {
  //передадим сюда через конструктор ObjectFactory
  private final ObjectFactory factory;

  @Override
  public void configure(Object t) throws ... {
    for (Field field : t.getClass().getDeclaredFields()) {
      if (field.isAnnotationPresent(InjectByType.class)) {
        field.setAccessible(true);
        //Мы же умеем по типу создавать объект?
        field.set(t, factory.createObject(field.getType()));
      }
    }
  }
}

Как создаётся и конфигурируется объект

public class ObjectFactory {
  //Правда, тут напрашивается DI?
  private final Reflections scanner =
                          new Reflections("edu.phystech");
  private final List<ObjectConfigurator> configurators =
                          new ArrayList<>();

  public <T> T createObject(Class<? extends T> type) throws ... {
    //Находим реализацию запрошенного типа
    type = resolveImpl(type);
    //Создаём объект (с помощью конструктора по умолчанию, TODO)
    T t = type.newInstance();
    //Конфигурируем
    configure(t);
    ....
  }

Метод configure очень прост

  private <T> void configure(T t) throws ... {
    for (ObjectConfigurator configurator : configurators) {
      configurator.configure(t);
    }
  }

Как находится подходящая имплементация

private <T> Class<? extends T> resolveImpl(Class<? extends T> type){
  if (type.isInterface()) {
    Set<Class<? extends T>> classes =
                         scanner.getSubTypesOf((Class<T>) type);
    if (classes.size() != 1) {
      throw new RuntimeException(
         "0 or more than one implementation found for type "
         + type + " please update your config");
    }
    type = classes.iterator().next();
  }
  return type;
}

Лектор-робот

robotlecturer
public class RobotLecturer {
    //«магическим» образом пусть тут появится то, что нужно!
    @InjectByType
    private Lecture lecture;
    @InjectByType
    private Speaker speaker;
    @InjectByType
    private SlideShow slideShow;
    ...
}

Режим лектора

//Читать лекции просто
public void lecture() {
    lecture.getSlides().forEach(
        slide -> {
            slideShow.show(slide.getText());
            speaker.speak(slide.getComment());
        }
    );
}

//Main-метод
public static void main(String[] args)
                  throws ReflectiveOperationException {
    RobotLecturer lecturer =
        new ObjectFactory().createObject(RobotLecturer.class);
    lecturer.lecture();
}

Конфигуратор объекта

@RequiredArgsConstructor
public class InjectByTypeAnnotationObjectConfigurator
                             implements ObjectConfigurator {
  //передадим сюда через конструктор ObjectFactory
  private final ObjectFactory factory;

  @Override
  public void configure(Object t) throws ... {
    for (Field field : t.getClass().getDeclaredFields()) {
      if (field.isAnnotationPresent(InjectByType.class)) {
        field.setAccessible(true);
        //Мы же умеем по типу создавать объект?
        field.set(t, factory.createObject(field.getType()));
      }
    }
  }
}

Как создаётся и конфигурируется объект

public class ObjectFactory {
  //Правда, тут напрашивается DI?
  private final Reflections scanner =
                          new Reflections("edu.phystech");
  private final List<ObjectConfigurator> configurators =
                          new ArrayList<>();

  public <T> T createObject(Class<? extends T> type) throws ... {
    //Находим реализацию запрошенного типа
    type = resolveImpl(type);
    //Создаём объект (с помощью конструктора по умолчанию, TODO)
    T t = type.newInstance();
    //Конфигурируем
    configure(t);
    ....
  }

Метод configure очень прост

  private <T> void configure(T t) throws ... {
    for (ObjectConfigurator configurator : configurators) {
      configurator.configure(t);
    }
  }

Как находится подходящая имплементация

private <T> Class<? extends T> resolveImpl(Class<? extends T> type){
  if (type.isInterface()) {
    Set<Class<? extends T>> classes =
                         scanner.getSubTypesOf((Class<T>) type);
    if (classes.size() != 1) {
      throw new RuntimeException(
         "0 or more than one implementation found for type "
         + type + " please update your config");
    }
    type = classes.iterator().next();
  }
  return type;
}

Let’s look for configurators automatically!

//ObjectFactory constructor
public ObjectFactory() throws ReflectiveOperationException {
  Set<Class<? extends ObjectConfigurator>> classes =
              scanner.getSubTypesOf(ObjectConfigurator.class);
  for (Class<? extends ObjectConfigurator> aClass : classes) {
    try {
      Constructor<? extends ObjectConfigurator> constructor =
                       aClass.getConstructor(ObjectFactory.class);
      //we inject ourselves through constructor, if needed
      configurators.add(constructor.newInstance(this));
    } catch (NoSuchMethodException e){
      configurators.add(aClass.newInstance());
    }
  }
....//to be continued

More configurators!

@Retention(RUNTIME)
public @interface InjectRandomInt {
    int min();
    int max();
}

InjectRandomIntObjectConfigurator

public class InjectRandomIntObjectConfigurator
                                 implements ObjectConfigurator {
  @Override
  public void configure(Object t) throws IllegalAccessException {
    Class<?> type = t.getClass();
    for (Field field : ReflectionUtils.getAllFields(type)) {
      InjectRandomInt annotation =
                        field.getAnnotation(InjectRandomInt.class);
      if (annotation != null) {
        int min = annotation.min();
        int max = annotation.max();
        int value = ThreadLocalRandom.current().nextInt(min, max+1);
        field.setAccessible(true);
        field.set(t, value);
      }
    }
  }
}

So, the first steps:

init1

Object Initialization

  • Why is the constructor not suitable for actions that require the injected values?

  • Injection may occur after constructor. Therefore, you need a special action that is called after constructor and injection!

PostConstruct

public class RobotLecturer {
  @InjectByType
  private Lecture lecture;
  @InjectRandomInt(min = 1, max = 3)
  private int repeat;

  @PostConstruct
  public void init() {
    //A place where all injected values can be used
    for (int i = 0; i < repeat; i++)
      speaker.speak("Hello everyone");
  }
  ...
}

Let’s continue to implement createObject

public <T> T createObject(Class<? extends T> type) throws ... {
  ....
  //Configuring
  configure(t);
  //running PostConstruct methods
  invokeInitMethods(type, t);
  ....
}

private <T> void invokeInitMethods(Class<? extends T> type, T t)
                                                      throws ... {
  for (Method method : type.getMethods()) {
    if (method.isAnnotationPresent(PostConstruct.class)) {
      method.invoke(t);
    }
  }
}

Sequence of actions

init2

Sometimes we need to modify the action of the method

@Retention(RUNTIME)
public @interface Benchmark {
}
[[[BENCHMARK method speak
Speaking: blah-blah-blah
Time: 107100ns]]]

Proxy object

proxy

BenchmarkProxyConfigurator

public class BenchmarkProxyConfigurator
                                     implements ProxyConfigurator {
  @Override
  public <T> T wrapWithPoxy(T t, Class<? extends T> type) {
    boolean isProxyNeeded = type.isAnnotationPresent(Benchmark.class)
      || !ReflectionUtils.getAllMethods(type, method ->
             method.isAnnotationPresent(Benchmark.class)).isEmpty();
    if (isProxyNeeded) {
      return (T) Proxy.newProxyInstance(type.getClassLoader(),
          type.getInterfaces(),
          (proxy, method, args) -> {
            Method classMethod = type.getMethod(method.getName(),
                                method.getParameterTypes());
            return invoke(t, type, method, args, classMethod);
          });
    }
    return t;
}}

Proxied method invocation

private Object invoke(Object t, Class type, Method method,
            Object[] args, Method classMethod) throws ... {
  if (classMethod.isAnnotationPresent(Benchmark.class)
        || type.isAnnotationPresent(Benchmark.class)) {
    System.out.printf("[[[BENCHMARK method %s%n", method.getName());
    long start = System.nanoTime();
    Object retVal = method.invoke(t, args);
    long end = System.nanoTime();
    System.out.printf("Time: %dns]]]%n", end - start);
    return retVal;
  } else {
    return method.invoke(t, args);
  }
}

Sequence of actions (final picture)

init3

Intermediate conclusions

  • DI-container implements the following stages of "setting up" objects:

    • instantiation

    • configuration (injections)

    • initialization (postconstruct)

    • proxying

  • DI pattern repeats itself: many DI container parts are convenient to configure via DI!

springframework

"Perhaps one of the hardest parts of explaining Spring is classifying exactly what it is" — Pro Spring 5, 5th ed., p. 1

Spring Framework

  • DI

  • AOP

  • Testing

  • Integration with a huge number of technologies

  • Very mature (and continuing to actively develop)

Переписываем наш пример с «самодельного» фреймворка на Spring

Before:

public class Main {
  public static void main(String[] args) throws ... {
    RobotLecturer lecturer = new ObjectFactory()
                     .createObject(RobotLecturer.class);
    lecturer.lecture();
  }
}

Переписываем наш пример с «самодельного» фреймворка на Spring

Стало:

@ComponentScan("edu.phystech.robotlecturer")
public class Main {
  public static void main(String[] args) {
    ApplicationContext ctx =
      new AnnotationConfigApplicationContext(Main.class);
    RobotLecturer lecturer = ctx.getBean(RobotLecturer.class);
    lecturer.lecture();
  }
}

Spring Beans

  • В нашем примере — 

    • RobotLecturer,

    • FirstLecture,

    • SpeakerImpl,

    • SlideShowImpl.

  • Spring beans — это переиспользуемые программные компоненты.

  • Годится любой класс, как наш, так и из сторонней библиотеки.

Spring configuration methods

  • Разновидности конфигураций Spring:

    • Annotation-based

    • XML-based

    • Groovy-based

  • Мы будем рассматривать только annotation-based, как наиболее употребимую в настоящее время и практичную.

  • В огромном количестве тьюториалов (и проектов) ещё встречается XML-конфигурация.

How to define beans

  • Classpath Scanning: ищем проаннотированные классы в заданных пакетах.

    • @Component

      • @Service

      • @Controller

      • @Repository

  • Фабричные методы

    • @Configuration → @Bean

Classpath scanning

@ComponentScan("edu.phystech.robotlecturer")

Annotation attributes:

  • String[] basePackages — базовые пакеты для сканирования в поисках аннотированных компонент.

  • Class<?>[] basePackageClasses — как типобезопасная альтернатива, можно указать классы. Пакеты каждого из указанных классов будут просканированы.

  • Плюсы: удобно.

  • Минусы: классы должны быть проаннторированы как @Component, @Service и т. п., что не всегда возможно для сторонних библиотек.

@Configuration class

  • Класс конфигурации должен быть либо явно указан через конструктор AnnotationConfigApplicationContext, либо доступен через сканирование пакетов (тогда нужно аннотировать класс как @Configuration).

  • In order to define beans, you need to use @Bean annotation.

@Configuration class example

@Configuration
public class AppConfig{

  @Bean
  @Scope(BeanDefinition.SCOPE_PROTOTYPE)
  public Color randomColor(){
    ThreadLocalRandom random = ThreadLocalRandom.current();
    return new Color(random.nextInt(256),
                random.nextInt(256), random.nextInt(256));
  }

  ...
}

Bean scope

  • SCOPE_SINGLETON is the default. Created only once at the first request and the single instance is injected everywhere.

  • SCOPE_PROTOTYPE — a new instance is created with each request.

  • There are many others, and you can create your own.

@Lazy

  • By default, all singletons are created when the container is started (to fail fast, and to avoid delays when the application is running).

  • For a specific bean, this behavior can be changed using the @Lazy annotation (see documentation).

  • Lazy initialization is not as good an idea as it seems at first glance.

Bean name

  • Each bean gets a name (id).

  • By default, the name is calculated from the class name (SpeakerImpl → ''speakerImpl'‘) or the name of the factory method (`getSpeaker → ’'speaker'’).

  • The name of the bean can be specified explicitly in the annotation parameter for @Component and other annotations (for example: @Service("bestSpeaker")).

Types of injection

  • Constructor

  • Setter

  • Field

  • Lookup method

Constructor injection

@Component
@RequiredArgsConstructor
public class RobotLecturer {
    //will be automatically passed to constructor
    private final Lecture lecture;
    private final Speaker speaker;
    private final SlideShow slideShow;
  • Внешне может быть незаметен (особенно с Lombok).

  • Хорош для создания иммутабельных объектов.

  • Много параметров конструктора? — А точно столько надо?

Setter injection

@Autowired
void setLecture(Lecture lecture) {
   //the setter will be automatically invoked after instantiation
   this.lecture = lecture;
}
  • Good in a situation where the component itself is able to provide a "default" dependency.

Field injection

@Component
public class RobotLecturer {
    //will be set via reflection after instantiation
    @Autowired
    private Lecture lecture;
    @Autowired
    private Speaker speaker;
    @Autowired
    private SlideShow slideShow;
  • Не плодит в классе сеттеры и конструкторы, но в целом сильно связывает код и считается не очень удачной практикой.

  • Хотя, в классах тестов — это ровно то, что нужно.

Lookup method injection

The problem of beans with different life cycles: SCOPE_PROTOTYPE won’t work.

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Bar {...}

@Component
public class Foo {
    @Autowired
    private Bar bar;

    public  void bar(){
        //заинжектированный экземпляр bar всегда один и тот же
    }
}

Lookup method injection

@Component
public abstract class Foo {
    @Lookup
    abstract Bar getBar();

    public  void bar(){
        Bar b = getBar();
        //теперь в b будет всякий раз новое (ну или одно и то же,
        //если убрать SCOPE_PROTOTYPE, хотя где тогда смысл?)
    }
}

Foo foo = ctx.getBean(Foo.class);
foo.bar(); foo.bar(); ...
  • What? do we instantiate an abstract class?! - No, we’re instantiating the wrapper, actually.

Lookup method may be not abstract

@Component
public class Foo {
    //the main thing is that it should not be private
    @Lookup
    Bar getBar(){
        return null;
    };
    public  void bar(){
        //not null!
        Bar b = getBar();
        ...
    }
}

Another approach: ObjectFactory injection

@Component
public class Foo {
    @Autowired
    private ObjectFactory<Bar> barFactory;

    public  void bar(){
        Bar bar = barFactory.getObject();
        ...
    }
}