Slide 1

Slide 1 text

Spring Boot Starter City Как??? Зачем?! магический лагерь для похудания

Slide 2

Slide 2 text

@tolkv @lavcraft @gorelikoff @gorelikov

Slide 3

Slide 3 text

Цели ● Развеять миф о магии в Spring Boot

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Цели ● Развеять миф о магии в Spring Boot ● Понять принципы работы экосистемы стартеров ○ посмотреть примеры из жизни

Slide 6

Slide 6 text

Цели ● Развеять миф о магии в Spring Boot ● Понять принципы работы экосистемы стартеров ● Понять прикладной смысл Spring Boot Starter ○ посмотреть примеры из жизни

Slide 7

Slide 7 text

Цели ● Развеять миф о магии в Spring Boot ● Понять принципы работы экосистемы стартеров ● Понять прикладной смысл Spring Boot Starter ● Как встраивать это в свою экосистему и куда двигаться дальше ○ посмотреть примеры из жизни

Slide 8

Slide 8 text

Цели ● Развеять миф о магии в Spring Boot ● Понять принципы работы экосистемы стартеров ● Понять прикладной смысл Spring Boot Starter ● Как встраивать это в свою экосистему и куда двигаться дальше + =

Slide 9

Slide 9 text

Spring уже не магия

Slide 10

Slide 10 text

Spring Boot все еще магия

Slide 11

Slide 11 text

Что такое Spring Boot? Эта jar-ник c Tomcat внутри Java interview 2014

Slide 12

Slide 12 text

Java interview 2017 Что такое Spring Boot? Эта хрень помогает проще собрать микросервис

Slide 13

Slide 13 text

@Getter @Setter @Aspect @ToString @EnableWs @Endpoint @EnableWebMvc @EnableCaching @Configuration @RestController @XmlRootElement @EnableWebSocket @RedisHash("cat") @EnableScheduling @EnableWebSecurity @NoArgsConstructor @ContextConfiguration @SpringBootApplication @Accessors(chain = true) @EnableAspectJAutoProxy @EnableAutoConfiguration @EnableRedisRepositories @EnableWebSocketMessageBroker // generate getters // generate setters // we are an aspect // generate toString() // SOAP is so enterprisy, we definitely need it // Seriously, just read above // we want MVC // and we want to cache stuff // this class can configure itself // we want some REST // this component is marshallable // we want web socket, it's so new-generation // this class is an entity saved in redis // we want scheduled tasks // and some built-in security // generate no args constructor // we want context configuration for unit testing // this is a Sprint Boot application // getters/setters are chained (ala jQuery) // we want AspectJ auto proxy // and auto configuration // since it is an entity we want to enable spring data repositories for redis // we want a broker for web socket messages

Slide 14

Slide 14 text

Но новичкам-то нравится

Slide 15

Slide 15 text

Пока не приходит Spring Boot инквизиция

Slide 16

Slide 16 text

Spring Boot слишком самостоятелен

Slide 17

Slide 17 text

Откуда 436 spring beans?

Slide 18

Slide 18 text

Откуда 436 spring beans?

Slide 19

Slide 19 text

Давайте разберёмся в “магии”

Slide 20

Slide 20 text

Кто был на “Spring is coming”?

Slide 21

Slide 21 text

Смотрим код Spring Boot’a

Slide 22

Slide 22 text

@SpringBootApplication

Slide 23

Slide 23 text

@SpringBootApplication @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication { …

Slide 24

Slide 24 text

@SpringBootApplication @EnableAutoConfiguration

Slide 25

Slide 25 text

@EnableAutoConfiguration @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import({EnableAutoConfigurationImportSelector.class}) public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class[] exclude() default {}; String[] excludeName() default {}; }

Slide 26

Slide 26 text

@SpringBootApplication @EnableAutoConfiguration ImportSelector

Slide 27

Slide 27 text

AutoConfigurationImportSelector protected List getCandidateConfigurations(...) { List configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); ... return configurations; }

Slide 28

Slide 28 text

@SpringBootApplication @EnableAutoConfiguration ImportSelector SpringFactoriesLoader

Slide 29

Slide 29 text

spring-boot-autoconfigure.jar/spring.factories org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\ org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\ org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration.\ … 129 lines

Slide 30

Slide 30 text

@SpringBootApplication @EnableAutoConfiguration ImportSelector SpringFactoriesLoader Starter#1 Starter#2 Starter#3

Slide 31

Slide 31 text

Ваше приложение

Slide 32

Slide 32 text

@ConditionalOnClass @ConditionalOnBean @ConditionalOnExpression @ConditionalOnProperty @ConditionalOnResource Загрузка при условии

Slide 33

Slide 33 text

Ну это boot, а при чем тут starter?

Slide 34

Slide 34 text

Как устроен стартер

Slide 35

Slide 35 text

Autoconfigure

Slide 36

Slide 36 text

Условия @Configuration @ConditionalOnBean({Client.class, DiscoveryClient.class}) @EnableConfigurationProperties(value = APIVersionFilterProperties.class) public class DiscoveryAPIVersionFilterAutoConfiguration { @Bean public ApiVersionServerListFilter versionedFilter(DiscoveryClient discoveryClient, APIVersionFilterProperties properties) { return new APIVersionServerListFilter(properties.getServiceVersions(), discoveryClient); } ... }

Slide 37

Slide 37 text

Конфигурация @Configuration @ConditionalOnBean({Client.class, DiscoveryClient.class}) @EnableConfigurationProperties(value = APIVersionFilterProperties.class) public class DiscoveryAPIVersionFilterAutoConfiguration { @Bean public ApiVersionServerListFilter versionedFilter(DiscoveryClient discoveryClient, APIVersionFilterProperties properties) { return new APIVersionServerListFilter(properties.getServiceVersions(), discoveryClient); } ... }

Slide 38

Slide 38 text

Starter

Slide 39

Slide 39 text

spring.factories org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ ru.alfalab.discovery.version.DiscoveryAPIVersionFilterAutoConfiguration

Slide 40

Slide 40 text

Вся магия 1. @EnableAutoConfiguration 2. @ConditionalOn… 3. spring.factories

Slide 41

Slide 41 text

Выводы часть #1 ● все не так сложно ● лишних бинов нет, грузится только то, что надо

Slide 42

Slide 42 text

Мы готовы писать свой стартер! Новичок #1 Новичок #2 Новичок #3 Новичок #4 Странный новичок

Slide 43

Slide 43 text

Стандартного набора хватит всем! Зачем писать свое? Опытный тех. лид А на практике

Slide 44

Slide 44 text

Из чего состоит сервис?

Slide 45

Slide 45 text

Из чего состоит сервис? ● API

Slide 46

Slide 46 text

Из чего состоит сервис? ● API ● Clients ○ JSON ○ SOAP

Slide 47

Slide 47 text

Из чего состоит сервис? ● API ● Clients ○ JSON ○ SOAP ● Cloud ○ Discovery ○ Config

Slide 48

Slide 48 text

Из чего состоит сервис? ● API ● Clients ○ JSON ○ SOAP ● Cloud ○ Discovery ○ Config ● Metrics ○ Healthcheck ○ Logs

Slide 49

Slide 49 text

Из чего состоит сервис? ● API ● Clients ○ JSON ○ SOAP ● Cloud ○ Discovery ○ Config ● Metrics ○ Healthcheck ○ Logs ● Data ● Stream

Slide 50

Slide 50 text

Смотрим код сервиса

Slide 51

Slide 51 text

Так это выглядит изнутри...

Slide 52

Slide 52 text

Так это выглядит изнутри...

Slide 53

Slide 53 text

Так это выглядит изнутри...

Slide 54

Slide 54 text

Так это выглядит изнутри...

Slide 55

Slide 55 text

Так это выглядит изнутри...

Slide 56

Slide 56 text

Так это выглядит изнутри...

Slide 57

Slide 57 text

Так это выглядит изнутри...

Slide 58

Slide 58 text

Этим сервисам стоило бы похудеть

Slide 59

Slide 59 text

Я не толстый! у меня кость широкая

Slide 60

Slide 60 text

Так это выглядит изнутри...

Slide 61

Slide 61 text

Что в этих классах

Slide 62

Slide 62 text

Service discovery

Slide 63

Slide 63 text

Межсервисное общение

Slide 64

Slide 64 text

Межсервисное общение

Slide 65

Slide 65 text

Простое общение с @FeignClient("cards-api") public interface P2PCardService { @RequestMapping(value = "/", method = RequestMethod.POST) CardDTO loadDetachedCard(String id); }

Slide 66

Slide 66 text

Межсервисное общение

Slide 67

Slide 67 text

Межсервисное общение

Slide 68

Slide 68 text

Межсервисное общение 1.0 1.0 1.0

Slide 69

Slide 69 text

Межсервисное общение 2.0 1.0 1.0

Slide 70

Slide 70 text

Отфильтруем друзей public class ServiceAPIVersionServerListFilter extends ZoneAffinityServerListFilter { ... @Override public List getFilteredListOfServers(List listOfServers) { if (listOfServers == null || listOfServers.isEmpty()) return listOfServers; List infos = this.discoveryClient.getInstances(listOfServers.first() .getMetaInfo() .getServiceIdForDiscovery()); final List versionedInstance = infos.stream() .filter(instanceInfo -> !versions.containsKey(instanceInfo.getServiceId().toLowerCase()) || checkVersion(versions.get(instanceInfo.getServiceId().toLowerCase()), instanceInfo.getMetadata().get(VERSION_FIELD))) .collect(Collectors.toList()); return listOfServers.stream() .filter(server -> checkServiceInstance(server, versionedInstance))

Slide 71

Slide 71 text

Отфильтруем друзей public class ServiceAPIVersionServerListFilter extends ZoneAffinityServerListFilter { ... @Override public List getFilteredListOfServers(List listOfServers) { if (listOfServers == null || listOfServers.isEmpty()) return listOfServers; List infos = this.discoveryClient.getInstances(listOfServers.first() .getMetaInfo() .getServiceIdForDiscovery()); final List versionedInstance = infos.stream() .filter(instanceInfo -> !versions.containsKey(instanceInfo.getServiceId().toLowerCase()) || checkVersion(versions.get(instanceInfo.getServiceId().toLowerCase()), instanceInfo.getMetadata().get(VERSION_FIELD))) .collect(Collectors.toList()); return listOfServers.stream() .filter(server -> checkServiceInstance(server, versionedInstance))

Slide 72

Slide 72 text

Отфильтруем друзей public class ServiceAPIVersionServerListFilter extends ZoneAffinityServerListFilter { ... @Override public List getFilteredListOfServers(List listOfServers) { if (listOfServers == null || listOfServers.isEmpty()) return listOfServers; List infos = this.discoveryClient.getInstances(listOfServers.first() .getMetaInfo() .getServiceIdForDiscovery()); final List versionedInstance = infos.stream() .filter(instanceInfo -> !versions.containsKey(instanceInfo.getServiceId().toLowerCase()) || checkVersion(versions.get(instanceInfo.getServiceId().toLowerCase()), instanceInfo.getMetadata().get(VERSION_FIELD))) .collect(Collectors.toList()); return listOfServers.stream() .filter(server -> checkServiceInstance(server, versionedInstance))

Slide 73

Slide 73 text

73 Это что?!

Slide 74

Slide 74 text

Много странного кода public class ServiceAPIVersionServerListFilter extends ZoneAffinityServerListFilter { ... @Override public List getFilteredListOfServers(List listOfServers) { if (listOfServers == null || listOfServers.isEmpty()) return listOfServers; List infos = this.discoveryClient.getInstances(listOfServers.first() .getMetaInfo() .getServiceIdForDiscovery()); final List versionedInstance = infos.stream() .filter(instanceInfo -> !versions.containsKey(instanceInfo.getServiceId().toLowerCase()) || checkVersion(versions.get(instanceInfo.getServiceId().toLowerCase()), instanceInfo.getMetadata().get(VERSION_FIELD))) .collect(Collectors.toList()); return listOfServers.stream() .filter(server -> checkServiceInstance(server, versionedInstance))

Slide 75

Slide 75 text

В нашем сервисе есть что-то инородное

Slide 76

Slide 76 text

Надо переносить в библиотеки

Slide 77

Slide 77 text

Стоп! Задумаемся

Slide 78

Slide 78 text

Стоп! Задумаемся Как конфигурировать?

Slide 79

Slide 79 text

Конфигурация фильтра eureka: client: registryFetchIntervalSeconds: 5 serviceUrl: defaultZone: ${EUREKA_SERV:http://127.0.0.1:8763/eureka/} instance: virtualHostName : ${spring.application.name} metadataMap: instanceId: ${spring.application.name}:${random.value} versions: 1.0 spring: discovery: filter: versions: someServiceId: 1.0

Slide 80

Slide 80 text

Конфигурация фильтра eureka: client: registryFetchIntervalSeconds: 5 serviceUrl: defaultZone: ${EUREKA_SERV:http://127.0.0.1:8763/eureka/} instance: virtualHostName : ${spring.application.name} metadataMap: instanceId: ${spring.application.name}:${random.value} versions: 1.0 spring: discovery: filter: versions: someServiceId: 1.0

Slide 81

Slide 81 text

Хочется видеть что-то такое spring: discovery: filter: versions: someOtherService: 1.0 api: versions: 1.0,2.0 2.0 1.0

Slide 82

Slide 82 text

Хочется видеть что-то такое spring: discovery: filter: versions: someOtherService: 1.0 api: versions: 1.0,2.0 2.0 1.0 1.0 2.0

Slide 83

Slide 83 text

spring: discovery: filter: versions: someOtherService: 1.0 api: versions: 1.0,2.0 Хочется видеть что-то такое 2.0 1.0 1.0 2.0 1.0 2.0

Slide 84

Slide 84 text

spring: discovery: filter: versions: someOtherService: 1.0 api: versions: 1.0,2.0 Хочется видеть что-то такое И проверять!!!

Slide 85

Slide 85 text

EnvironmentPostProcessor public class PropertyTranslatorPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication application) { } translateClientVersionProperty(env); translateZuulRoutes(env); } … }

Slide 86

Slide 86 text

EnvironmentPostProcessor`s Application ContextInitializer`s Application ReadyEvent Тут начинается Spring Ripper Application StartingEvent Application EnvironmentPreparedEvent Application PreparedEvent Context RefreshedEvent EmbeddedServlet Container InitializedEvent

Slide 87

Slide 87 text

EnvironmentPostProcessor`s Application ContextInitializer`s Application ReadyEvent Тут начинается Spring Ripper Application StartingEvent Application EnvironmentPreparedEvent Application PreparedEvent Context RefreshedEvent EmbeddedServlet Container InitializedEvent

Slide 88

Slide 88 text

@Configuration public class DiscoveryVersionFilterConfiguration { @Bean public void propertyTranslator() { } return new PropertyTranslatorPostProcessor(); } … } Создаём EPP

Slide 89

Slide 89 text

EnvironmentPostProcessor`s Application ContextInitializer`s Application ReadyEvent Тут начинается Spring Ripper Application StartingEvent Application EnvironmentPreparedEvent Application PreparedEvent Context RefreshedEvent EmbeddedServlet Container InitializedEvent

Slide 90

Slide 90 text

запуск SpringApplicationInitializer Локальные бины приложения созданы ApplicationEnvironment PreparedEvent запуск EnvironmentPostPorcessors Пользовательские бины создаются слишком поздно

Slide 91

Slide 91 text

Надо выносить в автоконфигурацию

Slide 92

Slide 92 text

Межсервисное общение 2.0 1.0 1.0

Slide 93

Slide 93 text

Дело не в spring-cloud ● Умное логирование ● Web-фильтры с доп. логикой ● Любая доп. логика общая для ваших сервисов

Slide 94

Slide 94 text

Выводы часть#2 Живешь со Spring - живи по правилам Spring. Доработка и расширение механизмов Spring должны быть в стартерах

Slide 95

Slide 95 text

Все еще много лишнего?

Slide 96

Slide 96 text

Все равно толстый!

Slide 97

Slide 97 text

Первый шаг к похуданию

Slide 98

Slide 98 text

Что у них общего?

Slide 99

Slide 99 text

Они общаются по SOAP XML

Slide 100

Slide 100 text

SOAP Services and Apache CXF ServiceDefinition.wsdl ...

Slide 101

Slide 101 text

SOAP Services and Apache CXF ServiceDefinition.wsdl ... Java Stub wsdl2java tool

Slide 102

Slide 102 text

SOAP Services and Apache CXF ServiceDefinition.wsdl Java Stub wsdl2java tool

Slide 103

Slide 103 text

SOAP Services and Apache CXF ServiceDefinition.wsdl Java Stub wsdl2java tool WS Stub in Spring Context Configure bean

Slide 104

Slide 104 text

SOAP Services and Apache CXF ServiceDefinition.wsdl Java Stub wsdl2java tool WS Stub in Spring Context Configure bean

Slide 105

Slide 105 text

SOAP Services and Apache CXF ServiceDefinition.wsdl Java Stub wsdl2java tool WS Stub in Spring Context Configure bean Call Bean Inject ws bean

Slide 106

Slide 106 text

SOAP Services and Apache CXF Apache CXF ServiceDefinition.wsdl Java Stub wsdl2java tool WS Stub in Spring Context Configure bean Call Bean Inject ws bean

Slide 107

Slide 107 text

SOAP Services and Apache CXF Apache CXF ServiceDefinition.wsdl Java Stub wsdl2java tool WS Stub in Spring Context Configure bean Call Bean Inject ws bean

Slide 108

Slide 108 text

CXF Stub в библиотеки

Slide 109

Slide 109 text

CXF Stub в библиотеки dependencies { compile 'ru.alfabank.ws:currency-stub:1.0.0' }

Slide 110

Slide 110 text

CXF Stub в библиотеки ws-stub transfers-api cards-api ...-api dependencies { compile 'ru.alfabank.ws:currency-stub:1.0.0' }

Slide 111

Slide 111 text

... WS – ты кто такой

Slide 112

Slide 112 text

... WS – ты кто такой

Slide 113

Slide 113 text

WS – ты кто такой transactions-api – ws.xml

Slide 114

Slide 114 text

WS – ты кто такой transactions-api – ws.xml targeting-api – ws.xml

Slide 115

Slide 115 text

WS – ты кто такой transactions-api – ws.xml targeting-api – ws.xml transfers-api – ws.xml ...

Slide 116

Slide 116 text

1. Добавить зависимость (WSDL/WS-STUB) 2. Настроить бины в ws.xml 3. Прописать адреса и настройки для добавленных сервисов ${lb.address.base} Как сделать новый RPC вызов

Slide 117

Slide 117 text

Как сделать новый RPC вызов 1. Добавить зависимость (WSDL/WS-STUB) 2. Настроить бины в ws.xml 3. Прописать адреса и настройки для добавленных сервисов ${lb.address.base} И как это делается?

Slide 118

Slide 118 text

Как сделать новый RPC вызов 1. Добавить зависимость (WSDL/WS-STUB) 2. Настроить бины в ws.xml 3. Прописать адреса и настройки для добавленных сервисов ${lb.address.base} И как это делается? Captain Copy-Paste

Slide 119

Slide 119 text

А что нужно разработчикам?

Slide 120

Slide 120 text

Сервис!

Slide 121

Slide 121 text

Run Application ERROR [-,,,] 27393 --- [main] o.s.boot.SpringApplication: Application startup failed Error creating bean with name 'ru.alfabank...WSAccountClickPayment13PortType' defined in Apache CXF starter autoscan package: Add next properties to your application.yml file: spring.cxf: clients: - endpoint: http://SOME_HOST/SOME_PATH_TO_WS className: ru.alfabank.ws.cs.eq.wsaccountclickpayment13.WSAccountClickPayment13PortType

Slide 122

Slide 122 text

ERROR [-,,,] 27393 --- [main] o.s.boot.SpringApplication: Application startup failed Error creating bean with name 'ru.alfabank...WSAccountClickPayment13PortType' defined in Apache CXF starter autoscan package: Add next properties to your application.yml file: spring.cxf: clients: - endpoint: http://SOME_HOST/SOME_PATH_TO_WS className: ru.alfabank.ws.cs.eq.wsaccountclickpayment13.WSAccountClickPayment13PortType Run Application

Slide 123

Slide 123 text

ERROR [-,,,] 27393 --- [main] o.s.boot.SpringApplication: Application startup failed Error creating bean with name 'ru.alfabank...WSAccountClickPayment13PortType' defined in Apache CXF starter autoscan package: Add next properties to your application.yml file: spring.cxf: clients: - endpoint: http://SOME_HOST/SOME_PATH_TO_WS className: ru.alfabank.ws.cs.eq.wsaccountclickpayment13.WSAccountClickPayment13PortType Process finished with exit code 1 Run Application

Slide 124

Slide 124 text

Автоматизируем? Classpath @WebService WSAccountClickPayment13PortType @WebService WSCardsTransactions12PortType @Component MySuperService @Other ...

Slide 125

Slide 125 text

Автоматизируем? Classpath @WebService WSAccountClickPayment13PortType @WebService WSCardsTransactions12PortType @Component MySuperService @Other ... Find WS Classes @WebService WSAccountClickPayment13PortType @WebService WSCardsTransactions12PortType

Slide 126

Slide 126 text

Автоматизируем? Classpath @WebService WSAccountClickPayment13PortType @WebService WSCardsTransactions12PortType @Component MySuperService @Other ... Find WS Classes @WebService WSAccountClickPayment13PortType @WebService WSCardsTransactions12PortType Spring Context BeanDefinition + BeanFactory WSAccountClickPayment13PortType BeanDefinition + BeanFactory WSCardsTransactions12PortType Configure Context

Slide 127

Slide 127 text

Автоматизируем? Spring Context BeanDefinition + BeanFactory WSAccountClickPayment13PortType BeanDefinition + BeanFactory WSCardsTransactions12PortType Inject Spring Context @Component MyService BeanInstance WSCardsTransactions12PortType Configure Properties and Endpoints

Slide 128

Slide 128 text

Автоматизируем? Spring Context BeanDefinition + BeanFactory WSAccountClickPayment13PortType BeanDefinition + BeanFactory WSCardsTransactions12PortType Inject Spring Context @Component MyService BeanInstance WSCardsTransactions12PortType Configure Properties and Endpoints Или падает с ошибкой если не настроен endpoint FAIL-FAST Error creating bean with name 'ru.alfabank...WSSomeServicet13PortType' defined in Apache CXF starter autoscan package: Add next properties to your application.yml file: spring.cxf: clients: - endpoint: http://SOME_HOST/SOME_PATH_TO_WS className: ru.alfabank....WSSomeServicet13PortType

Slide 129

Slide 129 text

EPP нет, можно в обычную библиотеку?

Slide 130

Slide 130 text

Как все это подключать? ● Чтение документации ● Debug ● Найти того, кто это писал...

Slide 131

Slide 131 text

@Slf4j @Configuration @EnableConfigurationProperties @ConditionalOnProperty(name = "spring.cxf.client.enabled", matchIfMissing = true) public class CxfClientConfiguration { @Bean public CxfBeanDefinitionPostProcessor cxfBeanDefinitionPP(Environment environment) { return new CxfBeanDefinitionPostProcessor(environment); } @Bean public static BusWiringBeanFactoryPostProcessor jsr250BeanPostProcessor() { return new BusWiringBeanFactoryPostProcessor(); } @Bean public static BusExtensionPostProcessor busExtensionPostProcessor() { return new BusExtensionPostProcessor(); } @Slf4j @Configuration @ConditionalOnClass({SpringBus.class, JaxWsClientFactoryBean.class, ConfigurationPropertiesBindingPostProcessor.class}) @EnableConfigurationProperties({CxfClientsProperties.class, WSConfiguration.class}) public static class CxfClientFactoryAutoConfiguration { @Bean(name = CXF_WS_CLIENT_PROXY_FACTORY_DEFAULT_NAME) @ConditionalOnMissingBean(name = {CXF_WS_CLIENT_PROXY_FACTORY_DEFAULT_NAME}) CxfWsStubBeanFactory proxyWsBeanFactory( CxfClientsProperties cxfClientsProperties, Bus bus, CxfInterceptorConfigurer interceptorConfigurer ) { return new CxfWsStubBeanFactory( cxfClientsProperties, bus, interceptorConfigurer ); } Конфигурация библиотек @Bean @ConditionalOnMissingBean(CxfBusConfigurer.class) public CxfBusConfigurer cxfBusConfigurer(CxfClientsProperties cxfClientsProperties) { return new DefaultCxfBusConfigurer(cxfClientsProperties); } @Bean(destroyMethod = "shutdown") public Bus cxf(CxfBusConfigurer cxfBusConfigurer) { SpringBus bus = new SpringBus(); cxfBusConfigurer.configure(bus); return bus; } @Bean @ConditionalOnMissingBean(CxfInterceptorConfigurer.class) public CxfInterceptorConfigurer cxfInterceptorConfigurer( CxfInterceptorAnnotationProcessor cxfInterceptorAnnotationProcessor, BeanFactory beanFactory ) { return new CxfInterceptorConfigurer( beanFactory, cxfInterceptorAnnotationProcessor.getGlobalInterceptors(), cxfInterceptorAnnotationProcessor.getSpecificInterceptors() ); } @Bean @ConditionalOnMissingBean(CxfInterceptorAnnotationProcessor.class) public static CxfInterceptorAnnotationProcessor cxfInterceptorBFPP() { return new CxfInterceptorAnnotationProcessor(); } static final String CXF_WS_CLIENT_PROXY_FACTORY_DEFAULT_NAME = "CxfWsClientProxyFactory"; } }

Slide 132

Slide 132 text

@Slf4j @Configuration @EnableConfigurationProperties @ConditionalOnProperty(name = "spring.cxf.client.enabled", matchIfMissing = true) public class CxfClientConfiguration { @Bean public CxfBeanDefinitionPostProcessor cxfBeanDefinitionPP(Environment environment) { return new CxfBeanDefinitionPostProcessor(environment); } @Bean public static BusWiringBeanFactoryPostProcessor jsr250BeanPostProcessor() { return new BusWiringBeanFactoryPostProcessor(); } @Bean public static BusExtensionPostProcessor busExtensionPostProcessor() { return new BusExtensionPostProcessor(); } @Slf4j @Configuration @ConditionalOnClass({SpringBus.class, JaxWsClientFactoryBean.class, ConfigurationPropertiesBindingPostProcessor.class}) @EnableConfigurationProperties({CxfClientsProperties.class, WSConfiguration.class}) public static class CxfClientFactoryAutoConfiguration { @Bean(name = CXF_WS_CLIENT_PROXY_FACTORY_DEFAULT_NAME) @ConditionalOnMissingBean(name = {CXF_WS_CLIENT_PROXY_FACTORY_DEFAULT_NAME}) CxfWsStubBeanFactory proxyWsBeanFactory( CxfClientsProperties cxfClientsProperties, Bus bus, CxfInterceptorConfigurer interceptorConfigurer ) { return new CxfWsStubBeanFactory( cxfClientsProperties, bus, interceptorConfigurer ); } Конфигурация библиотек @Bean @ConditionalOnMissingBean(CxfBusConfigurer.class) public CxfBusConfigurer cxfBusConfigurer(CxfClientsProperties cxfClientsProperties) { return new DefaultCxfBusConfigurer(cxfClientsProperties); } @Bean(destroyMethod = "shutdown") public Bus cxf(CxfBusConfigurer cxfBusConfigurer) { SpringBus bus = new SpringBus(); cxfBusConfigurer.configure(bus); return bus; } @Bean @ConditionalOnMissingBean(CxfInterceptorConfigurer.class) public CxfInterceptorConfigurer cxfInterceptorConfigurer( CxfInterceptorAnnotationProcessor cxfInterceptorAnnotationProcessor, BeanFactory beanFactory ) { return new CxfInterceptorConfigurer( beanFactory, cxfInterceptorAnnotationProcessor.getGlobalInterceptors(), cxfInterceptorAnnotationProcessor.getSpecificInterceptors() ); } @Bean @ConditionalOnMissingBean(CxfInterceptorAnnotationProcessor.class) public static CxfInterceptorAnnotationProcessor cxfInterceptorBFPP() { return new CxfInterceptorAnnotationProcessor(); } static final String CXF_WS_CLIENT_PROXY_FACTORY_DEFAULT_NAME = "CxfWsClientProxyFactory"; } }

Slide 133

Slide 133 text

Конфигурация библиотек @Bean public CxfBeanDefinitionPostProcessor cxfBeanDefinitionPP(Environment env) { return new CxfBeanDefinitionPostProcessor(env); } @Bean public static BusWiringBeanFactoryPostProcessor jsr250BeanPostProcessor() { return new BusWiringBeanFactoryPostProcessor(); } @Bean public static BusExtensionPostProcessor busExtensionPostProcessor() { return new BusExtensionPostProcessor(); }

Slide 134

Slide 134 text

Есть способ быстрее?!

Slide 135

Slide 135 text

Конфигурация библиотек Или, не дай бог : @ComponentScan( { "ru.alfa.cxf", "ru.alfa.discovery", "ru...", "ru..." ... } )

Slide 136

Slide 136 text

Проблемы 1. Необходимость знания кишков библиотек Капитан сложность Долой инверсию контроля!

Slide 137

Slide 137 text

Проблемы Толстый сервис 1. Необходимость знания кишков библиотек 2. Лишние куски кода в самом сервисе 3. Случайное подхваченные бины

Slide 138

Slide 138 text

Конфигурация стартеров внутри приложения

Slide 139

Slide 139 text

Не в SOAP дело ● Thrift/gRPC ● Netty ● Любая сложная или устаревшая внешняя зависимость

Slide 140

Slide 140 text

Вывод часть #3 Сложность конфигурации библиотеки иногда сопоставима со сложностью логики библиотеки

Slide 141

Slide 141 text

Вывод часть #3 Сложность конфигурации библиотеки иногда сопоставима со сложностью логики библиотеки Ее логичнее выносить в стартер

Slide 142

Slide 142 text

Вывод часть #3 Даешь инверсию контроля не только для компонентов Spring!

Slide 143

Slide 143 text

Умным сервисам - умные библиотеки

Slide 144

Slide 144 text

Похудел и накачался, но тормоз

Slide 145

Slide 145 text

Что значит тормоз? @ComponentScan @Service @Component

Slide 146

Slide 146 text

Бонусная секция

Slide 147

Slide 147 text

Что нового в Spring 5? Context Indexer

Slide 148

Slide 148 text

Просто добавь зависимость dependencies { compileOnly 'org.springframework:spring-context-indexer:5.0.1.RELEASE' }

Slide 149

Slide 149 text

Просто добавь зависимость dependencies { compileOnly 'org.springframework:spring-context-indexer:5.0.1.RELEASE' } # META-INF/spring.components o.s.t.f.APIVersionServerFilter=org.springframework.stereotype.Component o.s.t.f.APIVersionFilterHelper=org.springframework.stereotype.Component ...

Slide 150

Slide 150 text

Просто добавь зависимость dependencies { compileOnly 'org.springframework:spring-context-indexer:5.0.1.RELEASE' } # META-INF/spring.components o.s.t.f.APIVersionServerFilter=org.springframework.stereotype.Component o.s.t.f.APIVersionFilterHelper=org.springframework.stereotype.Component ... Классы связанный проаннотированный аннотацией Spring`а

Slide 151

Slide 151 text

Просто добавь зависимость dependencies { compileOnly 'org.springframework:spring-context-indexer:5.0.1.RELEASE' } # META-INF/spring.components o.s.t.f.APIVersionServerFilter=org.springframework.stereotype.Component o.s.t.f.APIVersionFilterHelper=org.springframework.stereotype.Component ... Чем проаннотировано

Slide 152

Slide 152 text

Выводы 1. Не магия, а скрытые возможности 2. Создавать стартеры просто и не грешно

Slide 153

Slide 153 text

Выводы 1. Не магия, а скрытые возможности 2. Создавать стартеры просто и не грешно 3. Инверсия контроля шире чем вы думаете

Slide 154

Slide 154 text

Выводы 1. Не магия, а скрытые возможности 2. Создавать стартеры просто и не грешно 3. Инверсия контроля шире чем вы думаете 4. Сложность перетекает постепенно и ее надо выносить из сервиса с бизнес-логикой по максимуму

Slide 155

Slide 155 text

Выводы 1. Не магия, а скрытые возможности 2. Создавать стартеры просто и не грешно 3. Инверсия контроля шире чем вы думаете 4. Сложность перетекает постепенно и ее надо выносить из сервиса с бизнес-логикой по максимуму Все стало проще? Да ладно?!

Slide 156

Slide 156 text

Это еще не конец Но он близко!

Slide 157

Slide 157 text

Стартеры тоже бывают разные Starter#1 Starter#2 Starter#3 spring-boot-autoconfigure

Slide 158

Slide 158 text

В чем разница? Starter#1 Starter#2 Starter#3

Slide 159

Slide 159 text

В чем разница? Starter#1 Starter#2 Starter#3 spring-boot-autoconfigure

Slide 160

Slide 160 text

Gradle transactions-api: dependencies { compile 'hazelcast:3.6.9' compile 'redis:1.1.1' compile 'mongodb:3.6.0' compile 'hazelcast-starter:1.0.0' compile 'redis-starter:0.2.0' compile 'mongodb-starter:0.2.0' … }

Slide 161

Slide 161 text

Gradle transactions-api: dependencies { compile 'hazelcast:3.6.9' compile 'redis:1.1.1' compile 'mongodb:3.6.0' compile 'hazelcast-starter:1.0.0' compile 'redis-starter:0.2.0' compile 'mongodb-starter:0.2.0' … } transactions-api: dependencies { compile 'hazelcast:3.6.9' compile 'redis:1.1.1' compile 'mongodb:3.6.0' compile 'fat-starter:100.50.0' }

Slide 162

Slide 162 text

Толстеем

Slide 163

Slide 163 text

Толстеем, Худеем

Slide 164

Slide 164 text

Толстеем, Худеем, Толстеем

Slide 165

Slide 165 text

Gradle transactions-api: dependencies { compile … compile … } offers-api: dependencies { compile … compile … } ...

Slide 166

Slide 166 text

Gradle transactions-api: dependencies { compile … compile … } offers-api: dependencies { compile … compile … } ... accounts-api: dependencies { compile … compile … } settings-api: dependencies { compile … compile … } ... transfer-api: dependencies { compile … compile … } payment-api: dependencies { compile … compile … } ...

Slide 167

Slide 167 text

Gradle transactions-api: dependencies { compile … compile … } offers-api: dependencies { compile … compile … } ... accounts-api: dependencies { compile … compile … } settings-api: dependencies { compile … compile … } ... transfer-api: dependencies { compile … compile … } payment-api: dependencies { compile … compile … } ... Captain Copy-Paste

Slide 168

Slide 168 text

Все немного разные

Slide 169

Slide 169 text

Сложно обновлять зависимости Все немного разные

Slide 170

Slide 170 text

Управляем зависимостями

Slide 171

Slide 171 text

build.gradle: apply plugin: "version.plugin" apply plugin: "maven.plugin" apply plugin: "check.plugin" apply plugin: "findbugs.plugin" apply plugin: "verify.plugin" apply plugin: "publish.plugin" apply plugin: "awesome.plugin" 171 Декларативный подход

Slide 172

Slide 172 text

● class MyPlugin implements Plugin { void apply(Project project) { project.configure { dependencies { compile … compile … } } } } Сила в композиции 172

Slide 173

Slide 173 text

Где достать зависимости? Application

Slide 174

Slide 174 text

Gradle знает Gradle plugin Application

Slide 175

Slide 175 text

Gradle знает где их искать Gradle plugin Application

Slide 176

Slide 176 text

Немножко магии Gradle plugin Application

Slide 177

Slide 177 text

Инверсия контроля для зависимостей !!! ug Application Redis starter HZ starter Mongo starter

Slide 178

Slide 178 text

Почему не хватает BOM?

Slide 179

Slide 179 text

Почему не хватает BOM? dependencies { gems 'asciidoctor-diagram:1.5.4.1' } asciidoctorj { version = '1.5.6' } task cleanTempDirs(type: Delete) { delete fileTree(dir: docsDir) } artifactoryPublish { properties = [artifactType: 'DOC'] } asciidoctor { finalizedBy tasks.withType(Zip) sources { include fileTree(dir: 'src/docs', includ include fileTree(dir: snippetsDir, inclu } dependsOn jrubyPrepare, project(':app').test gemPath = jrubyPrepare.outputDir requires = ['asciidoctor-diagram'] attributes 'source-highlighter': 'prettify', 'imagesdir': 'images', 'toc': 'left', 'icons': 'font', ...~200 lines

Slide 180

Slide 180 text

Почему не хватает BOM? dependencies { gems 'asciidoctor-diagram:1.5.4.1' } asciidoctorj { version = '1.5.6' } task cleanTempDirs(type: Delete) { delete fileTree(dir: docsDir) } artifactoryPublish { properties = [artifactType: 'DOC'] } asciidoctor { finalizedBy tasks.withType(Zip) sources { include fileTree(dir: 'src/docs', includ include fileTree(dir: snippetsDir, inclu } dependsOn jrubyPrepare, project(':app').test gemPath = jrubyPrepare.outputDir requires = ['asciidoctor-diagram'] attributes 'source-highlighter': 'prettify', 'imagesdir': 'images', 'toc': 'left', 'icons': 'font', ...~200 lines ugin

Slide 181

Slide 181 text

● class MyPlugin implements Plugin { void apply(Project project) { project.configure { dependencies { compile … compile … } } project.plugins.apply(AddGitTagPlugin) project.plugins.apply(UserInfoPlugin) } } Сила в композиции 181

Slide 182

Slide 182 text

● class MyPlugin implements Plugin { void apply(Project project) { project.configure { dependencies { compile … compile … } } project.plugins.apply(AddGitTagPlugin) project.plugins.apply(UserInfoPlugin) project.tasks.withType(SomeTaskType) { //configure } } } 182 Сила в композиции

Slide 183

Slide 183 text

Сила в композиции apply plugin: "your.plugin.all" //2.1.+ 183

Slide 184

Slide 184 text

Сила в композиции apply plugin: "your.plugin.all" //2.1.+ 184 Автоапдейт минорных версий Путь героев – но это уже другая история

Slide 185

Slide 185 text

И нет никаких проблем?

Slide 186

Slide 186 text

На больших проектах нужна инверсия контроля для сборки и зависимостей Вывод ...последний Gradle plugin

Slide 187

Slide 187 text

IoC Is Everywere

Slide 188

Slide 188 text

Вопросы?