dependency injection в java на примере эволюции spring — guice — cdi/weld

Download Dependency Injection в Java на примере эволюции Spring — Guice — CDI/Weld

Post on 15-Jun-2015

372 views

Category:

Education

6 download

Embed Size (px)

DESCRIPTION

Открытый семинар для студентов в компании CUSTIS (23 мая 2013). Лектор: Сергей Кошель, ведущий разработчик Java, аналитик. Аннотация: Из этого семинара вы узнаете о практическом применении паттерна Dependency Injection в мире Java и предоставляемых им возможностях на примере развития DI-фреймворков: от Spring и Guice до CDI/Weld. Формат встречи – динамичный с элементами Live Coding и демонстрацией особенностей реализации. Видеозапись семинара: https://vimeo.com/67125102.

TRANSCRIPT

  • 1. Dependency Injection Java Spring Guice CDI/Weld Java23 2013

2. 2/36 3. SimpleConverterFileSource DatabaseStorageAdapter3/36 4. + unit-public class Adapter {public void processMessage() {final FileSource fileSource = new FileSource();final SimpleConverter simpleConverter = new SimpleConverter();final DatabaseStorage databaseStorage = new DatabaseStorage();final Message inputMessage = fileSource.getMessage();final Message convertedMessage = simpleConverter.convert(inputMessage);databaseStorage.store(convertedMessage);}}4/36 5. MockConverterMockSource MockStorageFileSourceSimpleConverterDatabaseStorageSourceConverterStorageAdapter 5/36 6. public class Adapter {public void processMessage() {final Source source = SourceFactory.getSource();final Converter converter = ConverterFactory.getConverter();final Storage storage = StorageFactory.getStorage();final Message inputMessage = source.getMessage();final Message convertedMessage = converter.convert(inputMessage);storage.store(convertedMessage);}}6/36 7. @Testpublic void processMessage() throws Exception {SourceFactory.setSource(new MockSource("Hello from test!"));StorageFactory.setStorage(new MockStorage());final Adapter adapter = new Adapter();adapter.processMessage();// assert that...}+ () 7/36 8. public class Adapter {private Source source;private Converter converter;private Storage storage;public void setSource(Source source) {}public void setConverter(Converter converter) {}public void setStorage(Storage storage) {}public void processMessage() {final Message inputMessage = source.getMessage();final Message convertedMessage = converter.convert(inputMessage);storage.store(convertedMessage);}}8/36 9. @Testpublic void processMessage() throws Exception {final Adapter adapter = new Adapter();adapter.setSource(new MockSource("Hello from test!"));adapter.setConverter(new SimpleConverter());adapter.setStorage(new MockStorage());adapter.processMessage();// assert that...}+ :Setter based Dependency Injection by Hand9/36 10. public class Adapter {private final Source source;private final Converter converter;private final Storage storage;public Adapter(Source source, Converter converter, Storage storage) {this.source = source;this.converter = converter;this.storage = storage;}public void processMessage() {}}10/36 11. Dependency Injection (DI) (design pattern) ( , ) Inversion of Control (Hollywood principle Dont call us, well call you.)11/36 12. ? , , ,DI , , (loose coupling) DI 12/36 13. public class Adapter {public void processMessage() {final Source source = UniversalFactory.get("source", Source.class);final Converter converter = UniversalFactory.get("converter",Converter.class);final Storage storage = UniversalFactory.get("storage", Storage.class);final Message inputMessage = source.getMessage();final Message convertedMessage = converter.convert(inputMessage);storage.store(convertedMessage);}}+ : Service Locator13/36 14. DI SL DI SL , 14/36 15. IoC- DI AOP 15/36 16. Disclaimer 16/36 17. Spring Framework17/36 18. * , 18/36 19. final ApplicationContext applicationContext= new ClassPathXmlApplicationContext("spring-config.xml");adapter = applicationContext.getBean("adapter", Adapter.class);+ + Spring+ - 19/36 20. Autowiring20/36 21. Lifecycle Management singleton prototype []applicationContext.destroy();21/36 22. @Scope(SCOPE_SINGLETON)public class Adapter {private Source source;private Converter converter;private Storage storage;@Autowiredpublic void setSource(Source source) {}@Autowiredpublic void setConverter(Converter converter) {}@Autowired(required = false)public void setStorage(Storage storage) {}@PostConstructpublic void init() {}@PreDestroypublic void close() {}} 22/36 23. 23/36@Autowired@Qualifier("source")public void setSource(Source source) {} , 24. Google Guice24/36 25. Pure Java configpublic class AdapterModule extends AbstractModule {@Overrideprotected void configure() {bind(SimpleConverter.class);bind(Source.class).to(FileSource.class);bind(Storage.class).toInstance(new DatabaseStorage());}}final Injector injector = Guice.createInjector(new AdapterModule());adapter = injector.getInstance(Adapter.class);25/36 26. Annotation based@Singletonpublic class Adapter {private final Source source;private final Converter converter;private final Storage storage;@Injectpublic Adapter(Source source, Converter converter, Storage storage) {this.source = source;this.converter = converter;this.storage = storage;}public void processMessage() {}}* , 26/36 27. Pure Java configpublic class AdapterModule extends AbstractModule {@Overrideprotected void configure() {}@ProvidesSource fileSource() {return new FileSource();}}* Spring 3.0 JavaConfig27/36 28. Provider interfacepublic interface Provider {T get();}bind(Validator.class).to(SimpleValidator.class);public class Adapter {private Provider validator;@Injectpublic void setValidator(Provider validator) {}public void processMessage() {...validator.get().validate(inputMessage);...}}28/36 29. Provider interface (, ) (the new new) 29/36 30. 30/36@BindingAnnotation@Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)public @interface FileBased {}@Injectpublic Adapter(@FileBased Source source, Converter converter, Storage storage) {}bind(Source.class).annotatedWith(FileBased.class).to(FileSource.class);+ Typesafe 31. CDI/WeldJSR 299: Contexts and Dependency Injectionfor the Java EE platformWeld reference implementationfor JSR-29931/36 32. CDI Guice DSL @Produce classpath @Inject, @Sengleton,Provider . . EJB-32/36 33. Instance Provider ProviderInstance extends Provider if (instance.isUnsatisfied()) {} if (instance.isAmbiguous()) {for (T t : instance) {...}} (SL)adapter = instance.select(Adapter.class).get();33/36 34. Eventpublic class Adapter {@InjectEvent adapterStartedEvent;@PostConstructpublic void init() {adapterStartedEvent.fire(new AdapterStarted());}}public class AnyOtherManagedBean{public void onAdapterStart(@Observes AdapterStarted adapterStarted) {}}34/36 35. AOP method intercepting Scopes 35/36 36. !? skoshel@custis.ru36/36