Developers want to make very few errors in their code and to spot them as early as possible: with the help of unit tests, or earlier, during compilation, or best of all, immediately after they typed something wrong in their IDE. This is what static code analyzers are for. Some of them are built-in, others need to be run separately, some check just about any code, the others require it to be annotated first, and there are tools that are a little bit of all. Do the ends justify the means? Is it even worth trying? What kind of errors can be spotted by static code analysis? How sure can we be if what an analyzer gives us is a real error or a false positive? This talk hopefully helps you answer these questions.
Why should we know about Spring internals? It works! So use it and enjoy! However, as always, in order to use Spring in most efficient way, you must know, what is under the fork. Only in case you really understand its internals you will be able to use all power of Spring. You will be able to customize this framework according to challenges of your project, to achieve best performance and solve any problem without applying to Spring-support center. ;) Here are several topics about Spring internals, which will be covered during this session (with examples for each one): What is Spring impact on the performance of your application? What are the phases of Spring lifecycle? What is ApplicationContext structure? “You can’t do it with Spring!” – or maybe you can?
Особенности тестирования Spring Boot приложения. Нововведения с версии spring-boot 1.4.+
В программе:
* Старые подходы
** @ContextConfiguration
** @ContextHierarchy && @DirtiesContext
** @ActiveProfiles
* Что нового нам приготовил Spring Boot?
** @SpringBootTest
** @TestConfiguration
** @SpringBootConfiguration и его связь с @SpringBootApplicatoin
** @MockBean && @SpyBean && @*Beans
** @DataJpaTest
** @WebMvcTest
* Кэширование spring контекстов
* Шкала тестов
* Порядок сканирвоания контекста test+main. Подводные камни этого процесса
Слайды с доклада "Проклятие Spring Boot Test" на JUG в рамках РИФ Воронеж
Developers want to make very few errors in their code and to spot them as early as possible: with the help of unit tests, or earlier, during compilation, or best of all, immediately after they typed something wrong in their IDE. This is what static code analyzers are for. Some of them are built-in, others need to be run separately, some check just about any code, the others require it to be annotated first, and there are tools that are a little bit of all. Do the ends justify the means? Is it even worth trying? What kind of errors can be spotted by static code analysis? How sure can we be if what an analyzer gives us is a real error or a false positive? This talk hopefully helps you answer these questions.
Why should we know about Spring internals? It works! So use it and enjoy! However, as always, in order to use Spring in most efficient way, you must know, what is under the fork. Only in case you really understand its internals you will be able to use all power of Spring. You will be able to customize this framework according to challenges of your project, to achieve best performance and solve any problem without applying to Spring-support center. ;) Here are several topics about Spring internals, which will be covered during this session (with examples for each one): What is Spring impact on the performance of your application? What are the phases of Spring lifecycle? What is ApplicationContext structure? “You can’t do it with Spring!” – or maybe you can?
Особенности тестирования Spring Boot приложения. Нововведения с версии spring-boot 1.4.+
В программе:
* Старые подходы
** @ContextConfiguration
** @ContextHierarchy && @DirtiesContext
** @ActiveProfiles
* Что нового нам приготовил Spring Boot?
** @SpringBootTest
** @TestConfiguration
** @SpringBootConfiguration и его связь с @SpringBootApplicatoin
** @MockBean && @SpyBean && @*Beans
** @DataJpaTest
** @WebMvcTest
* Кэширование spring контекстов
* Шкала тестов
* Порядок сканирвоания контекста test+main. Подводные камни этого процесса
Слайды с доклада "Проклятие Spring Boot Test" на JUG в рамках РИФ Воронеж
Обсудим что нового в Spring Boot Test 1.4.0+
В программе:
* Старые подходы
** @ContextConfiguration
** @ContextHierarchy && @DirtiesContext
** @ActiveProfiles
* Что нового нам приготовил Spring Boot?
** @SpringBootTest
** @TestConfiguration
** @MockBean && @SpyBean && @*Beans
** @DataJpaTest
** @WebMvcTest
* Кэширование spring контекстов
* Шкала тестов
Слайды с доклада "Проклятие Spring Boot Test"
Особенности тестирования Spring Boot приложения. Нововведения с версии spring-boot 1.4.+
В программе:
* Старые подходы
** @ContextConfiguration
** @ContextHierarchy && @DirtiesContext
** @ActiveProfiles
* Что нового нам приготовил Spring Boot?
** @SpringBootTest
** @TestConfiguration
** @SpringBootConfiguration и его связь с @SpringBootApplicatoin
** @MockBean && @SpyBean && @*Beans
** @DataJpaTest
** @WebMvcTest
* Кэширование spring контекстов
* Шкала тестов
* Порядок сканирвоания контекста test+main. Подводные камни этого процесса
Слайды с доклада "Проклятие Spring Boot Test"
Применение behave+webdriver для тестирования Web-проектовPyNSK
Докладчик:
Иван Гребенщиков
Описание:
Современные веб-проекты представляют из себя совсем не набор статических страниц, что повышает сложность их функционального тестирования.
В докладе будет рассмотрена связка инструментов behave+webdriver, способе их применения, возможные проблемы и пути их решения.
Все разработчики автоматизированных тестов рано или поздно сталкиваются с проблемой - "то, что есть в тулзе, которую я юзаю, явно не достаточно и надо что-то делать".
Мы поговорим с чего начать и чем продолжить, так чтоб получить действительно хорошее решение для автоматизированного тестирования. Обсудим интеграцию с continues integration и реализации систем репортинга. За опорный пример возьму фреймворк на базе Selenium.
«JSSDK: Начало» Когда использовать готовые решения, а когда писать самим. Какие шаги нужно сделать, чтобы ваша работа не оказалась напрасной и принесла пользу окружающим. Все эти нюансы будут рассмотрены на примере внутреннего фреймворка, который возник вследствие необходимости объединения кодовой базы двух проектов.
Фреймворк Akka и его использование в ЯндексеVadim Tsesko
Доклад с JPoint 2014 (http://javapoint.ru).
Краткое содержание:
* Actor Model на примере Akka
* Происхождение
* Концепции и API
* Примеры кода
* Примеры систем в Яндекс
* Конвейерная обработка данных
* Реактивные иерархические системы
* Опыт разработки и эксплуатации
* Подводные камни
* Проблемы и некоторые решения
* Дополнительные тулы
Обсудим что нового в Spring Boot Test 1.4.0+
В программе:
* Старые подходы
** @ContextConfiguration
** @ContextHierarchy && @DirtiesContext
** @ActiveProfiles
* Что нового нам приготовил Spring Boot?
** @SpringBootTest
** @TestConfiguration
** @MockBean && @SpyBean && @*Beans
** @DataJpaTest
** @WebMvcTest
* Кэширование spring контекстов
* Шкала тестов
Слайды с доклада "Проклятие Spring Boot Test"
Особенности тестирования Spring Boot приложения. Нововведения с версии spring-boot 1.4.+
В программе:
* Старые подходы
** @ContextConfiguration
** @ContextHierarchy && @DirtiesContext
** @ActiveProfiles
* Что нового нам приготовил Spring Boot?
** @SpringBootTest
** @TestConfiguration
** @SpringBootConfiguration и его связь с @SpringBootApplicatoin
** @MockBean && @SpyBean && @*Beans
** @DataJpaTest
** @WebMvcTest
* Кэширование spring контекстов
* Шкала тестов
* Порядок сканирвоания контекста test+main. Подводные камни этого процесса
Слайды с доклада "Проклятие Spring Boot Test"
Применение behave+webdriver для тестирования Web-проектовPyNSK
Докладчик:
Иван Гребенщиков
Описание:
Современные веб-проекты представляют из себя совсем не набор статических страниц, что повышает сложность их функционального тестирования.
В докладе будет рассмотрена связка инструментов behave+webdriver, способе их применения, возможные проблемы и пути их решения.
Все разработчики автоматизированных тестов рано или поздно сталкиваются с проблемой - "то, что есть в тулзе, которую я юзаю, явно не достаточно и надо что-то делать".
Мы поговорим с чего начать и чем продолжить, так чтоб получить действительно хорошее решение для автоматизированного тестирования. Обсудим интеграцию с continues integration и реализации систем репортинга. За опорный пример возьму фреймворк на базе Selenium.
«JSSDK: Начало» Когда использовать готовые решения, а когда писать самим. Какие шаги нужно сделать, чтобы ваша работа не оказалась напрасной и принесла пользу окружающим. Все эти нюансы будут рассмотрены на примере внутреннего фреймворка, который возник вследствие необходимости объединения кодовой базы двух проектов.
Фреймворк Akka и его использование в ЯндексеVadim Tsesko
Доклад с JPoint 2014 (http://javapoint.ru).
Краткое содержание:
* Actor Model на примере Akka
* Происхождение
* Концепции и API
* Примеры кода
* Примеры систем в Яндекс
* Конвейерная обработка данных
* Реактивные иерархические системы
* Опыт разработки и эксплуатации
* Подводные камни
* Проблемы и некоторые решения
* Дополнительные тулы
Four Hands is a model for thinking about individuals within organisations, and builds off of the work done by Kenneth Hopper and William Hopper in their book, The Puritan Gift.
Financial Portfolio Management with Java on Steroids - JAX Finance 2016aixigo AG
Marcus Gründler talks about high performance software at the JAX Finance 2016 conference in London.
Analyzing financial transactions data of a large number of portfolios and hundreds of millions transactions and quotes is a demanding job for any computing environment.
Analysis systems don't necessarily have extremely low latency requirements such as trading systems do, but have to provide low user response times. Applying massive parallelism over CPU cores or even clusters of machines doesn't help much if you want to achieve response times of a few milliseconds.
Unleashing the extreme power of todays CPUs with a stream oriented architecture - which is optimal for utilizing caches and branch prediction of modern CPUs - becomes the corner stone in such systems.
The talk presents insights into a system that is based on the idea of multi version concurrency control (MVCC) using Apache Kafka and binary in-memory data representation. Learn how to achieve speed improvements of a factor of 100-200 times compared to classic object oriented design.
Designing Solr schema and different use cases in e-commerce world. This is our experience with Solr Schema and how it evolved while building multi-tenant search platform.
Presentation by Mohit Jain
У нас было 500 страниц спецификаций, 40000 строк кода, 2 офиса, полдюжины разработчиков, а также целое множество андроидов всех сортов и расцветок. Не то, чтобы это был необходимый запас для приложения крупной торговой сети. Но если начал собирать софт, становится трудно остановиться. Единственное, что вызвало у меня опасение — это сетевая библиотека. Нет ничего более беспомощного, безответственного и испорченного, чем писать AsyncTask на каждый вызов. Я знал, что рано или поздно мы перейдём на Event Bus.
Август 2014, DevDay, Новосибирск
Олег Годовых «Страх и ненависть в Event Bus»DevDay
У нас было 500 страниц спецификаций, 40000 строк кода, 2 офиса, полдюжины разработчиков, а также целое множество андроидов всех сортов и расцветок. Не то, чтобы это был необходимый запас для приложения крупной торговой сети. Но если начал собирать софт, становится трудно остановиться. Единственное, что вызвало у меня опасение — это сетевая библиотека. Нет ничего более беспомощного, безответственного и испорченного, чем писать AsyncTask на каждый вызов. Я знал, что рано или поздно мы перейдём на Event Bus.
Любите ли вы велосипеды? Все разработчики любят свои ненаколеночныерешения велосипеды! И мы не исключение. В нашем докладе мы покажем как собирать, сколачивать, вылепливать собственный велосипед так, чтобы на нем потом могла ездить без слёз вся команда, компания, или может весь мир.
Что в докладе будет:
- много Spring Boot-а;
- live coding;
- создание собственного Spring Boot Starter-а;
- Apache Thrift в качестве подопытного кролика.
Чего не будет:
- бенчмарков и сравнений Thrift vs REST vs gRPC vs XXX.
О сложностях программирования, или C# нас не спасет?Tatyanazaxarova
Программирование это сложно. С этим никто, надеюсь, не спорит. Но вот тема новых языков программирования, а точнее поиск "серебряной пули" всегда находит бурных отклик в умах разработчиков программного обеспечения. Особенно "модной" является тема превосходства одного языка программирования над другим. Ну, к примеру, что C# "круче", чем C++. И хотя holy wars – это не та причина, по которой я пишу этот пост, тем не менее, что называется "наболело". Ну не поможет C#/lisp/F#/Haskell/... написать изящное приложение, взаимодействующее с внешним миром, и все тут. Вся изящность теряется, стоит захотеть написать что-то реальное, а не пример "сам в себе".
Сергей Шамбир, Адаптация Promise/A+ для взаимодействия между C++ и JavascriptSergey Platonov
Шаблоны — мощный инструмент, добавляющий в язык новые возможности, а программистам в команде — новые проблемы. Доклад покажет, как тщательно продуманный шаблонный код может не усложнить, а упростить жизнь и дать надёжную абстракцию межпроцессных межъязыковых асинхронных вызовов функций. С помощью шаблонов можно:
адаптировать Promise/A+ из Javascript для C++
автоматически проверять и раскладывать динамический массив аргументов на статичные аргументы функции
сделать аналог std::bind для weak_ptr.
Эти вещи будут показаны на примере взаимных вызовов между C++ и Javascript в одном приложении с помощью CEF3.
The Epic Groovy Puzzlers S02: The Revenge of the ParenthesesJavaDayUA
More strange, more bizarre, more fun! The Groovy Puzzlers hits with its second season in which we implemented the lesson learned from the first one – do more of the same (always as a duet)! Expect even more “NO WAY!”, “WHOA!”, “WTF!”, O_o and prizes flying around, and expect to learn more about Groovy’s darkest secrets! As usual, the traps we fell into here in JFrog and contributions from top-notch Groovy authors and users!
Есть такая штука как инструментирование кода. Мало кто знает о ней, даже пользуясь результатами ее применения. Между тем, с инструментированием можно делать много всего интересного и, главное, полезного. Например, это может вам помочь лучше понять код или сделать процесс разработки более эффективным. Примеры инструментирования кода и принципы его работы.
Выполняет анализ кода на языках: C, C++, C++/CLI, C++/CX, C#. Plugin для Visual Studio 2010-2015. Интеграция с SonarQube, QtCreator, CLion, Eclipse CDT, Anjuta DevStudio и т.д. Быстрый старт (мониторинг компиляции). Прямая интеграция анализатора в системы автоматизации сборки и утилита BlameNotifier (рассылка писем). Режим автоматического анализа изменённых файлов. Почему нужны анализаторы кода?
Язык C++ и инфраструктура вокруг него продолжает активно развиваться, что делает этот язык одним из самых эффективных инструментов в настоящее время. Хочется выделить три фактора, делающие язык C++ сейчас столь привлекательным. Первое: нововведения в стандарт языка, позволяющие писать эффективный код. Второе: зрелость инструментов разработки и увеличение скорости сборки проектов. Третье: зрелось вспомогательного инструментария, позволяющие контролировать качество кода и другие аспекты жизненного цикла проекта. Этот доклад - ода языку программирования C++!
Сейчас только ленивый не говорит про DevOps, краеугольным камнем которого является организация потока непрерывной доставки ценности клиенту. Continuous Delivery перестаёт быть опцией и становится обязательным требованием.
В докладе будут рассмотрены:
- общие подходы к организации Continuous Delivery на базе Jenkins-а в совсем не тепличных условиях
- практики и подходы, которые позволяют быстро настраивать и собирать десятки микросервисов
- подводные камни, с которыми пришлось столкнуться, и способы борьбы с ними
Статический анализ кода: Что? Как? Зачем?Andrey Karpov
Методология статического анализа год за годом зарекомендовывает себя в поисках дефектов в исходном коде программ.
Максим расскажет про:
- методологию статического анализа и какие плюсы и минусы у нее есть;
- технологии этой методологии, которые позволяют выявлять разнообразнейшие дефекты в коде;
- интересные примеры ошибок в реальных проектах, которые были найдены при помощи статического анализа;
- интеграцию инструментов статического анализа в проекты любой сложности, и почему так важно регулярное использование подобных инструментов.
Similar to Spring Puzzlers by Evgeny Borisov, Baruch Sadogursky (20)
Science, Technology, Engineering and Mathematics, STEM, are vital to the future of our children. The parents and students in our educational systems need to understand and embrace the technology that affects them every day of their lives. Devoxx4Kids is on a global mission to complement the classical schooling system by offering workshops to kids in a fun way. and teaching them computing concepts using Scratch, Greenfoot, Minecraft, Raspberry Pi, Arduino, NAO, Tynker. We will share a path that can be followed by adults to keep kids in their vicinity engaged and build, instead of just play, games. You will learn best practices to organize similar workshops in your local setting and hear tips on opening a local chapter. This talk will be appreciated by anybody who has kids, nephews, nieces, and in general kids around them.
Writing concurrent code that is also correct is unbelievably hard. Naturally, humanity has developed a number of approaches to handle concurrency in the code, starting from basic threads that follow the hardware way to do concurrency to higher level primitives like fibers and work-stealing solutions. But which approach is the best for you? In this session, we'll take a look at a simple concurrent problem and solve it using different ways to manage concurrency: threads, executors, actors, fibers, monadic code with completable futures. All these approaches are different from the simplicity, readability, configuration and management point of view. Some scenarios are better modelled with threads, while sometimes you're better off with actors. We'll discuss the benefits of each approach and figure out when it's worth pursuing in your project.
До выхода Feature Complete версии OpenJDK 9 EA остался месяц. Самое время посмотреть, что ждет нас в следующей версии Java. Для начала рассмотрим процесс того, как идеи становятся JEP-ами, а потом становятся частью стандарта языка Java. Потом посмотрим на список из четрех десятков фич, разберем наименее тривилаьные из них на примерах: jshell, jmh, unified jvm logging и, конечно же, модулярность.
Continuously building, releasing and deploying software: The Revenge of the M...JavaDayUA
We used to release one product, once a year, built by one team. Today we have teams of hundreds of developers creating a multitude of software packages that are released multiple times a day.How did that happen?! In this talk, we’ll give you the answer: As the good old advice of Computer Science goes, “If it hurts, do it more often!”. Suddenly, we realized that what we do during the “Release Month Code Freeze” is actually a lot of repeatable, automatable steps. So, we called in the machines.Now we have Continuous Integration servers controlling an exponential amount of robot developers (agents) that are building and testing our code, all day long. Continuous Deployment tools, dictating their order to robot sysadmin, deploying our software on a rapidly increasing amount of varied platforms, as frequent as we please.The Machines got their revenge, and “we, for ones, welcome our new robotic overlords”!
This keynote will be a historical trip down memory lane - going through 20 years of Java and JVM implementations. This will be partly from Marcus’s own perspective as one of the architects behind JRockit, with plenty of stories from the trenches, like the benchmarking competitions between BEA/Oracle, Sun and IBM. We will see how Java and the JVM turned into the robust high performance server side platform that it is today, partly through personal observations and partly through a more objective “what a long strange trip this has been”. He will take you back to 1995 in a time machine and slowly bring you to 2014, going over the major Java releases and the runtime innovations made in the JVM side to get us here. Finally, we will do a short trip into the future, even though the future is always fuzzy, to explore what might be coming next. With Java 8, the biggest release in Java history, Java is more vibrant and alive than ever before. This is an evolution that won’t be stopped.
As developers we always look for ways to do things faster, better, and automate as much as possible. We write code in top-notch IDEs that have static code analysis, automatic refactoring and so on, we run unit tests, we use CI servers, and issue trackers, we adopt agile practices to get feedback and deliver as fast as possible. As far as code review practice goes, there’s still a lot to be improved, and in this talk I’m going to tell you how you can perform efficient, transparent and useful code reviews.
Unlocking the Magic of Monads with Java 8JavaDayUA
This code-heavy session demystifies what monads are and outlines reasons why you would even want to introduce them into your code. We’ll take a look at the traditional definition for monads and offer a corresponding type definition in Java. We’ve selected a sample Java 8 implementation of a ‘Promise’ monad, which represents the result of async computation to help us answer practical questions about monads. Also, we'll go over the Laws of Monads and show that you can have a proper monad in Java, if you are brave enough to allow the underlying platform change the rules a bit. PS. You won’t be penalised or ridiculed during this session for your (lack of) Haskell knowledge!
Virtual Private Cloud with container technologies for DevOpsJavaDayUA
DevOps with Containers in Virtual Private Cloud and Hybrid Cloud. A new opportunity for hosting providers to attract Enterprise customers. Containers have changed the mind of IT in DevOps. They enable developers to work with dev, test, stage and production environments identically. Containers provide the right abstraction for Microservices and many cloud platforms have integrated them into deployment pipelines. DevOps and Containers together help companies to achieve their business goals faster and more effectively. At this session we will review the current landscape of DevOps with Containers and the benefits for hosting providers. In addition, we will discuss known issues and solutions for enterprise applications in Containers.
JShell: An Interactive Shell for the Java PlatformJavaDayUA
Read-Execute-Print-Loops (REPLs) have emerged as powerful tools for learning and prototyping. JShell brings this power to Java. Targeted for JDK 9, and tightly integrated with the Java compiler and virtual machine, JShell enhances the programming experience for the Java language. Learn how to use JShell to explore new APIs, prototype code, or learn the Java language. Interactively explore new features of JDK 9. See the features that speed up coding.
Interactive Java Support to your tool -- The JShell API and ArchitectureJavaDayUA
Explore the JShell API. Learn how it can be used to add interactive Java expression/declaration execution to new or existing tools. See how the completion functionality can enhance code editors or analyzers. Get a behind the scenes look at the JShell architecture and its deep integration with the Java platform.
MapDB - taking Java collections to the next levelJavaDayUA
Java collections have several limitations. But imagine library without limits, which could even replace your database. This session talks about drop-in replacement with many new possibilities. MapDB provides Java collections backed by in-memory or on-disk store. It adds extra features to traditional collections (entry expiration, binding, secondary collections…). It is also proper database engine and has transactions, snapshots, incremental backups… And finally it is not affected by GC, so it can take a billion entries without a hiccup.
Java heap memory model has wasteful memory usage. References, object headers, internal collection structure, extra fields such as String.hashCode… This talk shows practical ways to reduce memory usage and fit more data into memory: primitive types, specialized java collections, bit packing, reducing number of pointers, replacing String with char[], semi-serialized objects… As bonus we get lower GC overhead by reducing number of references.
The JRockit JVM was originally developed by Appeal Virtual Machines as a from scratch server-side JVM in order to compete with HotSpot from Sun Microsystems. Appeal Virtual Machines was acquired by BEA Systems in 2002, which in turn became part of Oracle in 2010. JRockit is battle proven in the commercial space as a high performance server JVM and has unique monitoring and manageability capabilities for doing zero overhead instrumentation of production systems. This talk covers the design rationales that the JRockit architects did in code generation, memory management, synchronization and serviceability. The JRockit and HotSpot JVMs are currently in the process of being merged into one code base, most of which will be part of the OpenJDK.
Next-gen DevOps engineering with Docker and Kubernetes by Antons KrangaJavaDayUA
Docker is in font of container madness that forces us to rethink our entire architecture and development practices. This session will be focusing around building Java runtimes on Docker containers and running it with Kubernetes. We will focus on different deployment aspects specific to the Docker and Kubernetes and utilise DevOps engineering managed by Jenkins.
Some previous knowledge of docker is not required however advised
Apache Cassandra. Inception - all you need to know by Mikhail DubkovJavaDayUA
Cassandra is a powerful NoSql database based on solid fundamentals of distributed computing and fail-safe design, and it is well-tested by companies such as Facebook, Twitter, and Netflix. Unlike conventional databases and some of the modern databases that use the master-slave pattern, Cassandra uses the all-nodes-the-same pattern; this makes the system free from a single point of failure.
Solution Architecture tips & tricks by Roman ShramkovJavaDayUA
In this presentation we will cover:
* What is Solution Architecture and how it differs from other architectures
* What is good and what is bad for SA, tips & tricks from our experience
Testing in Legacy: from Rags to Riches by Taras SlipetsJavaDayUA
In this presentation I'd like to share practical experience and techniques that were used for modernization and maintaining 10+ years old legacy system: pitfalls that we've faced during that process and conclusions that we'd made when we've successfully finished updating mission.
Reactive programming and Hystrix fault tolerance by Max MyslyvtsevJavaDayUA
Reactive programming is a new paradigm that provides asynchronous event-based flow control. Java implementation is called rxJava and is being developed by Netfix. They have also released Hystrix — a non-functional layer that provides fault tolerance and latency features which also exposes reactive API.
Spark-driven audience counting by Boris TrofimovJavaDayUA
The story about Ad world and real-time segments counting. Size of data does not allow doing straightforward calculations so we will dive into the solution step-by step involving some "secret" algorithms from Google.
API first with Swagger and Scala by Slava SchmidtJavaDayUA
How does one scale the development of a service landscape in a corporate enterprise environment utilizing Typesafe's Play and Akka software stack? How does one achieve API uniformity and coherence accross dozens of development teams, getting them and their subsequently developed subsystems to play together nicely? At Zalando we believe firmly in an API first approach, founded an API guild that ratifies and supports the development of APIs, and define them in a formal manner employing the Swagger API representation language.
12. Аннотации Cпринга в наследовании
public class Parent {
@PostConstruct
private void init(){
System.out.println("Папа");
}
}
@Component
public class Son extends Parent {
@PostConstruct
public void init(){
System.out.println("Cын");
}
}
Создаём сына, что с папой?
A. @PostConstruct не inherited,
Поэтому Папа не придёт
B. init у Папы private,
поэтому Папа не придёт
C. Не может быть больше, чем один
init method – Папа не придёт
D. init method переопределён у
сына, поэтому папа не придёт
E. Папа придёт
14. Аннотации спринга в наследовании
public class Parent {
@PostConstruct
private void init(){
System.out.println("Папа");
}
}
@Component
public class Son extends Parent {
@PostConstruct
public void init(){
System.out.println("Cын");
}
}
Создаём сына, что с папой?
A. @PostConstruct не inherited,
Поэтому Папа не придёт
B. init у Папы private,
поэтому Папа не придёт
C. Не может быть больше, чем один
init method – Папа не придёт
D. init method переопределён у
сына, поэтому папа не придёт
E. Папа придёт
15.
16. @Service
public class JavadayServiceImpl implements JavadayConfService {
@Autowired
private String cityName;
@Audit
public void pay() {
…
}
@PostConstruct
public void init(){
…
}
}
Добавляем наш @Audit
A. Не сработает init method
B. NoSuchBeanDefinitionException
C. Упадёт Autowired из за то, что у
прокси нет нужного филда
D. Не сработает аспект
E. Всё будет хорошо
context.getBean(JavadayConfService.class).pay();
17.
18. @Service
public class JavadayServiceImpl implements JavadayConfService {
@Autowired
private String cityName;
@Audit
public void pay() {
…
}
@PostConstruct
public void init(){
System.out.println(cityName);
}
}
Добавляем наш @Audit
A. Не сработает init method
B. NoSuchBeanDefinitionException
C. Упадёт Autowired из за то, что у
прокси нет нужного филда
D. Не сработает аспект
E. Всё будет хорошо
context.getBean(JavadayConfService.class).pay();
19. Как мы это чиним?
• Прокси надо делать после инит методов!
• Для это есть postProcessAfterInit
20. @Component
@Aspect
public class PayInformatorAspect {
@Pointcut("execution(* javaday..*.pay*(..))")
public void allPayMethods(){}
@After("allPayMethods()")
public void sendMailToAndrey(){
System.out.println("Ещё билет продали");
}
}
Добавим Аспект
A. Андрей получит извещение о проданном билете, но не аудита
B. Аудит будет, но Андрей не узнает о проданном билете
C. Будет аудит и Андрей получит извещение
D. Будет exception из-за двухуровневого прокси
21.
22. Как мы это чиним?
• Пишем нормальный BPP, который не делает
bean.getClass()
26. @JavadayTransaction
public class JavadayConfService {
public void transferMoney(Account from, Account to, BigDecimal amount) {
withdraw(from, amount);
deposit(to, amount);
}
@Transactional(propagation = Propagation.MANDATORY)
private void withdraw(Account from, BigDecimal amount) {
//some code here
}
@Transactional(propagation = Propagation.REQUIRED)
private void deposit(Account to, BigDecimal amount) {
//some code here
informBankManager(amount);
}
private void informBankManager(BigDecimal amount) {
//some code here
}
}
Вложенные транзакции
C. Откатится до начала
метода deposit
D. Метод withdraw
кинет exception
A. Всё откатится
до самого начала
B. Откатится только
informBankManager
Случился exception
в методе
informBankManager.
Что будет?
27.
28. Почему не работает??
@Service
public class JavadayConfServiceImpl implements JavadayConfService {
@Transactional
public void transferMoney(Account from, Account to, BigDecimal amount)
…
informAboutPayment();
}
@Override
@Transactional(requiresNew = true)
public void informAboutPayment() {
System.out.println("money were transferred");
}
}
29. Почему не работает??
@Service
public class JavadayConfServiceImpl implements JavadayConfService {
@Transactional
public void transferMoney(Account from, Account to, BigDecimal amount)
…
this.informAboutPayment();
}
@Override
@Transactional(requiresNew = true)
public void informAboutPayment() {
System.out.println("money were transferred");
}
}
38. @Service
public class JavadayServiceImpl implements JavadayConfService
{
@Transactional
@PostConstruct
public void warmCache() {
…
}
@Override
public void processPayment() {
…
}
}
39. @Transactional @PostConstruct
• Что будет, с методом у которого обе аннотации?
A. Сработает с транзакцией
B. Сработает без транзакции
C. Не сработает вообще
D. MethodMissingException
56. Что будет?
@Service
public class MissionCriticalService {
@PostConstruct
public void important(){
System.out.println("Не забудь выключить утюг!");
}
}
<bean class="javaday.littlegirl.MissionCriticalService"/>
<context:component-scan base-package=“javaday.littlegirl"/>
@Bean
public MissionCriticalService missionCriticalService() {
return new MissionCriticalService();
}
A. не забыть выключить
утюг
B. не забыть выключить
утюг *2
C. не забыть выключить
утюг *3
D. BeanCreationException
57.
58. Смотрим!
@Service
public class MissionCriticalService {
@PostConstruct
public void important(){
System.out.println("Не забудь выключить утюг!");
}
}
<bean class=“javaday.littlegirl.MissionCriticalService"/>
<context:component-scan base-package="javaday.littlegirl"/>
@Bean
public MissionCriticalService missionCriticalService() {
return new MissionCriticalService();
}
59. Выводы
1. Учите спринг!
2. Читайте документацию
3. Иногда это баги, И Иногда их
можно починить
4. Пользуйте spring integration в
intellij IDEA!
5. Учите спринг, Я сказал!