ТОП популярных вопросов o Spring Framework за 13 минут … — Transcript

Popular Spring Framework questions answered with examples, covering Spring Boot, bean scopes, annotations, and configuration methods.

Key Takeaways

  • Spring Boot simplifies dependency management and reduces boilerplate code.
  • Singleton beans are created once per Spring context, while prototype beans are created per request but only once per singleton injection.
  • Multiple annotations exist to create Spring beans, and custom annotations are possible.
  • Bean configuration can be done via XML, Java, or annotations, each with its use cases.
  • Java configuration is essential when dealing with third-party classes that cannot be annotated.

Summary

  • Introduction to the most popular Spring Framework questions relevant for developers.
  • Explanation of what Spring Boot solves, focusing on reducing code and managing dependency compatibility.
  • Discussion of Spring Boot starters like Spring Starter Web and WebFlux with embedded Tomcat.
  • Detailed explanation of Spring bean scopes: singleton and prototype, including lifecycle behavior.
  • Clarification on how many times prototype beans are created when injected into singleton beans.
  • Overview of annotations used for creating beans: @Bean, @Component, @Service, @RestController, @Controller, @Repository, and custom annotations.
  • Description of the three main ways to configure beans: XML, Java configuration, and annotation-based configuration.
  • Insight into why Java configuration is needed despite the convenience of annotations, especially for third-party classes without Spring annotations.
  • Emphasis on the importance of understanding bean lifecycle and configuration methods for different experience levels.
  • Encouragement to deepen knowledge beyond junior-level answers for middle and senior developers.

Full Transcript — Download SRT & Markdown

00:01
Speaker A
[музыка] Friends, hello everyone! You are on the DBA channel, and Max Dobrynin welcomes you again.
00:26
Speaker A
What interesting things await us today? Let's go and find out together. In this video, we will analyze the most popular questions about the Spring framework. You can encounter questions like these anywhere, so
00:39
Speaker A
you 100% must know all this and be ready in case someone asks you about it. And if you consider yourself a cool Spring specialist, well then, let's check. I will state these questions, and you try to answer them. So,
01:02
Speaker A
friends, let's go and find out these questions together and get [музыка] answers to them. The first question is my favorite: what task does Spring Boot solve? Actually, the question is ambiguous; there are several possible answers. First, of course, it is about how much code you can
01:20
Speaker A
reduce with just one simple file. You don't need to create beans, you don't need to link them together; everything works automatically out of the box. You only need to connect the appropriate starter and then add configuration values. Naturally,
01:39
Speaker A
it won't work just like that in all cases. This happens only in starters like Spring Starter Web or WebFlux, where Tomcat deploys itself and immediately launches a ready-made app with standard configurations already predefined by Spring Boot itself. There is no magic, just time-saving.
01:57
Speaker A
Historically, the Spring Framework has a huge number of various dependencies that it creates and supports itself. I have listed a few of the most popular ones: Spring Context, Spring Web, Spring Security, and so on. This list can go on endlessly. And if you go to
02:18
Speaker A
a public repository, you will see an endless list of these dependencies. Here lies the problem: many dependencies, each with its own version. How do you maintain compatibility between them? Historically, developers using Spring did this themselves. They
02:34
Speaker A
took a specific version of a module, then another module, and another, and then checked the release notes and how everything interacted during program startup. This process is quite complicated because release notes do not always contain information about which dependencies are compatible with each other. For this reason, developers often had to do this manually by adding dependencies to the application, running it, and checking that everything actually worked. As you understand, this consumed a huge amount of time, which is not efficient, especially by modern standards. And this problem is exactly what Spring Boot is designed to solve. It has a so-called Bill of Materials, which we know as Spring Dependencies or Spring Boot Parent. The idea is quite simple: there is only one version, and that is enough for us because Spring Boot itself defines all the necessary dependencies with exactly that version, which will be compatible with other dependencies. Thus, we can confidently say that Spring Boot itself solves the problem of dependency compatibility, and the developer only needs to use one version of Spring Boot and enjoy all the features of this solution.
02:51
Speaker A
Everyone without exception knows that the key unit of the Spring framework is a bean. Yes, that famous POJO. And as you probably guess, every key entity must have its own lifecycle. So here comes the related question: what are the main scopes for a bean in the Spring framework? The answer is simple: the first is singleton, and the second is prototype. The difference between them is not very big. As you can imagine, singleton is a typical implementation of the singleton design pattern, meaning a single instance. For us as developers, this means only one thing: once the bean is created, no one else will create it. In other words, in a Spring application, such a bean can exist only in one instance. On the other hand, what is prototype? How does it differ? It might seem to hint at the prototype design pattern, but it is not exactly that. The main difference between prototype and singleton is that a prototype bean will be initialized every time the Spring context requests that bean as part of another bean. It is also called a collaborator bean. Another interesting question that follows from the scope of these beans is: how many times will a prototype bean be created as part of a singleton bean? In other words, the task is simple: imagine we have a bean declared as singleton, and it has a property, and the value for this property should be an instance of another bean, which is the collaborator bean. In other words, a bean that participates directly in the lifecycle of another bean. And here comes the tricky question: if a prototype bean is intended for injection every time it is requested by a singleton, strange as it sounds, the prototype bean will be created exactly as many times as its singleton bean carrier is created. Well, you probably already understood the answer: if the singleton exists in one instance, then the prototype will also exist in one instance. However, here is a catch. If you are a junior, this is a perfectly decent answer. But if you are a middle, senior, or higher, I would dig a little deeper because no one forbids us from requesting the same bean in the same Spring context but as a collaborator for a completely different bean. Thus,
03:07
Speaker A
we will have two calls to the prototype bean: one as part of one singleton and probably another as part of another singleton. And voila, in one Spring context, we get two instances of a bean with prototype scope. As I said, this is a tricky question. Beans, beans, beans — as we know, everything revolves around beans in Spring. One of the most popular questions is: how can we create these beans, or more precisely, with which annotations? And here, friends, we have quite a few options. We can easily list them: @Bean, @Component, @Service, @RestController, just @Controller, @Repository. And of course, you can create your own custom annotations for creating beans. You are definitely not limited in this as developers, only if there is a technical reason for it. And since we talked about creating beans with annotations, it is quite natural to expect the question: what ways of configuring beans exist? After all, annotation is just one method. The answer here is as simple as before: we have XML configuration, Java configuration, and annotation-based configuration, the example we just discussed a moment ago. But again, if you are a junior, this is a perfectly decent answer. Why not? I personally would answer this way if I were a junior. But if you are a middle, senior, or as I said, higher, more is expected from you. One of the common questions sounds like this: why do we need Java configuration when we have convenient annotation-based configuration? Especially since the famous Spring Boot solution works perfectly with annotations, and essentially the developer only needs to annotate and enjoy the instance of this class as a bean in the Spring context. But here, friends, let's think. Imagine an ordinary developer who has a task, and in the process of its implementation, he needs to create several beans. He has a class, and everything is fine. But suddenly, this developer discovers that these classes were developed and supplied by a third-party company, and it turns out these classes exist in the classpath only as part of a JAR, that is, a connected library. Naturally, the developers of that company created a regular API without burdening themselves with any specific framework, for example, Spring. Think about how you will create an instance of a bean based on annotations if you simply cannot put an annotation on such a class.
03:26
Speaker A
использовать одну версию спринг бута и наслаждаться всеми возможность этого решения все без исключения знают что ключевой единицей фреймворка Spring является Бин Да тот самый знаменитый Боб и как вы уже все догадываетесь У любой ключевой сущности должен быть свой
03:46
Speaker A
жизненный цикл Вот вам и вытекающий Вопрос какие есть основные скопы для бина в фреймворке Spring Ответ здесь короче не придумаешь первый синглтон и второй - это друзья прота между ними разница не уж большая Как можно себе представить singl Tone - это типичное
04:04
Speaker A
творение шаблона проектирования singl Tone то есть одиночка для нас как разработчиков это значит всего лишь одно что в тот момент когда Бин был создан то больше никто создавать Его не будет иначе говорю в спринговый приложении такой Бин может существовать лишь в
04:19
Speaker A
одном экземпляре с другой стороны Что такое прото тайп Чем отличается ведь Казалось бы он намекает на шаблон проектирования прота Однако это не так Главное отличие прота от singleton заключается в том что прота как Бин будет инициализировать каждый раз когда
04:36
Speaker A
СН контекст затребуваний данного бина как часть другого бина он же называется Бин коллаборатор другим не мене занимательным вопросом который в свою очередь вытекает из скоупа этих бинов является следующее выражение сколько раз Бин прота будет создан как часть бина силтон иначе говоря задача
04:58
Speaker A
простая представим себе у нас есть с вами Bean который объявляется как Single Tone и у него есть свойство и в качестве значения для этого свойства должен быть подключён экземпляр другого бина и это тот самый Бин коллаборатор и иначе
05:12
Speaker A
говоря такой Бин который принимает непосредственное участие в жизненном цикле другого бина и тут-то и возникает тот самый хитрый вопрос Если бенко прота предназначен для внедрения Каждый раз когда его затребуваний сингл тона как бы странно не звучало Бин прота создаст ровно столько раз сколько
05:33
Speaker A
будет создан его Бин носитель со скопом Single Tone Ну ответ вы уже наверняка поняли если синглтон существует в одном экземпляре соответственно и этот прото тайп будет существовать тоже в одном экземпляре Однако здесь есть подвох Если вы джун то Вполне себе достойный ответ
05:49
Speaker A
но если вы midle или сир или что-нибудь повыше то я бы немножко копнул ведь Никто не запрещает нам затребовать тот же самый Бин в части того же Spring текста но уже в качестве коллаборатор для абсолютно другого бина Таким образом
06:05
Speaker A
у нас будет два вызова бина прота один в части одного сингл тона И вероятно в другой тоже в части другого сингл тона и Вуаля в одном спринг контексте мы получаем два экземпляра Бине со скопом прота Ну как я уже сказал это вопрос со
06:20
Speaker A
звёздочкой бины бины бины как мы уже знаем всё крутится вокруг бина в этом спринг и один из популярнейших вопросов Каким образом мы эти бины собственно можем создавать а точнее при помощи каких аннотаций и тут друзья возможностей у нас довольно-таки много Мы можем с
06:39
Speaker A
лёгкостью их перечислить это bin это компонент это сервис это рест контроллер это просто контроллер это репозиторий И разумеется можно создавать свои собственные аннотации для создания бинов вы в этом уж точно не ограничены как разработчики был бы только для этого
06:56
Speaker A
технический смысл и Коль уж мы с вами заговорили о создании бинов при помощи аннотаций то Вполне себе закономерно ожидать вопрос А какие вообще способы конфигурирования бинов существуют ведь аннотация - Это всего лишь один из видов и здесь друзья ответ такой же простой
07:12
Speaker A
как и предыдущий У нас есть xml конфигурация есть Java конфигурация а также конфигурация основанная на аннотация пример который мгновение назад мы с вами разобрали но всегда И сно если ты джун опять же это вполне себе достойный ответ Почему бы и нет ну я Я
07:30
Speaker A
лично бы так на месте Джуна бы отвечал бы но если ты midle или синер или как Я уже сказал что-нибудь повыше побольше от вас будет ожидать немножко больше И один из из любых вопросов звучит следующим образом Зачем нам необходима Java
07:43
Speaker A
конфигурация Когда у нас есть удобная конфигурация основана на аннотация Тем более что знаменитое решение Spring Boot отлично работает на аннотация и по сути разработчику ничего не остаётся кроме как повешать и наслаждаться экземпляром этого класса в виде вина в спринг
07:58
Speaker A
контексте но вот здесь друзья давайте-ка задумаемся представим себе рядового разработчика у него есть задача и в процессе её реализации ему необходимо создать несколько бинов у него есть класс и всё отлично но вдруг данный разработчик обнаруживает что что данные
08:13
Speaker A
классы были разработаны И поставляются вообще сторонние компании и оказывается что данные классы существуют в класс пасе только как часть жарки то есть по сути подключённая библиотека само собой разработчики той компании создавали обычный API вовсе не обременять себя какого-то конкретного фреймворка
08:31
Speaker A
например того же спрингар Задумайтесь сами каким образом вы будете создавать экземпляр бина на основание аннотации если на такой класс вы аннотацию попросту повешать не можете Да вот так не задача и вот тут друзья и вступает тот самый Java config Он
08:47
Speaker A
позволяет нам по сути в ручном режиме выбрать класс который должен быть кандидатом в бины собственно ручками создаём экземпляр данного класса а метод который возвращает экземпляр данного класса маркирует Bean и тут Важно отметить что когда вы используете аннотацию Bean над методами
09:05
Speaker A
очень важно чтобы данные методы были частью класса над которым друзья стоит другая аннотация которая называется configuration и вот это друзья и есть тот самый пример почему бы стоило применять Java конфигурацию И вообще зачем она существует как часть фреймворка
09:21
Speaker A
Spring чтот сегодня мы с вами Много говорим о бина и Следующий вопрос конечно же тоже не обойдёт эти бины ведь как я уже отметил ранее это Краеугольный камень который лежит в основе фреймворка Spring собственно вопрос Каким образом сприн присваивает уникальное имя бину
09:38
Speaker A
ведь каким-то образом он уникально должен существовать в спринг контексте и более того когда вы попытаетесь создать два экземпляра одного и того же бина Вы скорее всего словить вот эту ошибку думаю каждый из вас с не когда-либо сталкивался собственно ответ если мы
09:53
Speaker A
используем конфигурацию основанную на аннотация то Как вы догадываетесь имя бина будет браться с имени классом стоит данная аннотация и Дада Друзья кто не знал аннотация configuration - это тоже тип бина и соответственно даже если это конфигурационный класс призванный
10:09
Speaker A
создавать бины то всё равно он является Бином и тоже обладает именем в спринг контексте Ну а что касается бинов которые были созданы при помощи аннотации bein которую мы цепляем поверх методов Ну не сложно догадаться имя класса он брать не будет Он попросту
10:23
Speaker A
возьмёт имя метода и данным именем будет нарен вновь созданный be Все мы использовали аннотацию автова Каждый раз когда в спринг контексте не существует Бин который эта аннотация по сути затребуваний к внедрению То есть к коллаборации но такой Бин К сожалению в спринг контексте
10:45
Speaker A
найден не был очень часто всё прозрачно скорее всего мы забыли такой Бин проинициализировать правильно Ну допустим не отмар его аннотацией либо не создали соответствующий Java config либо Java config не подтягивается либо ещё что похуже Но это всё такое ведь вопрос
11:00
Speaker A
в большей степени стоит А что если данный Бин всё-таки опциональный и выходит что нельзя эту аннотацию вовсе вешать и она нас постоянно будет принуждать к тому что Бин должен существовать И что тогда мы будем вынуждены делать какие-то заглушки
11:15
Speaker A
вместо этого бина на тот случай когда его попросту не существует нет друзья если мы откроем конфигурацию данной аннотации то мы увидим поле required и это собственно поле по умолчанию стоит True То есть каждый Бин который должен быть под включён в соответствии с этой
11:31
Speaker A
аннотацией должен неизбежно существовать в контексте но а если вы считаете что для вашей бизнес логики не каждый Бин должен создаваться это вполне себе может быть да не частый кейс но может быть Вот тогда собственно значение этого проперти меняется на Фолс И разумеется сприн
11:47
Speaker A
знает как правильно реагировать на ситуацию когда Бин был затребованный Ден в спринг контексте не был вот такие вопросы друзья а что думаешь ты пиши в комментарии смог бы ответить или вообще расширил бы этот список какими-то своими крутыми вопросами на тему фреймворка сприн лайк
12:10
Speaker A
подписка комментарии всё это очень сильно приветствуется к чему вас призывает Это позволяет нам развиваться на просторах юту и в целом в интернете и не забывайте про нашу инициативу а проди а также не забывайте про наш крутой Telegram канал вы там найдёте всё что
12:23
Speaker A
вас интересует и Неважно кто вы новичок или техлит каждый раз необходимо обновлять свои знания и быть в теме современ трендо а на сегодня это всё друзья пока-пока До новых встреч [музыка]
Topics:Spring FrameworkSpring BootJava configurationBean scopesSingleton beanPrototype beanSpring annotationsDependency managementSpring Boot startersSpring context

Frequently Asked Questions

What main problem does Spring Boot solve?

Spring Boot solves the problem of dependency compatibility and reduces boilerplate code by providing a Bill of Materials that manages versions of dependencies automatically, allowing developers to use one version and have compatible dependencies out of the box.

What are the main bean scopes in Spring Framework?

The main bean scopes are singleton, where only one instance of a bean exists per Spring context, and prototype, where a new instance is created every time the bean is requested from the Spring context.

Why is Java configuration still needed if annotations are so convenient?

Java configuration is necessary when dealing with third-party classes that cannot be annotated with Spring annotations, such as classes in external JARs. It allows manual creation and registration of beans, which annotations alone cannot handle.

Get More with the Söz AI App

Transcribe recordings, audio files, and YouTube videos — with AI summaries, speaker detection, and unlimited transcriptions.

Or transcribe another YouTube video here →