VHow does dependency injection work in Spring?
Питання інтерв’юераSpring
Інтерв’юери на Spring-позиції хочуть почути, що ви розумієте, що відбувається за анотаціями. Фрази «@Autowired просто працює» недостатньо. Потрібно сказати, як контейнер створює та зв’язує біни.
Добра структура усної відповіді: яку проблему розв’язує можливість, як вона влаштована всередині фреймворку та один підводний камінь із реального проєкту. Підводні камені роблять відповідь схожою на досвід, а не на завчене.
- ✓Слова → фрази → речення → мовлення
- ✓Зміст відповіді
- ✓Мова
Поширені запитання та зразки відповідей
How does dependency injection work in Spring?
Як працює впровадження залежностей (dependency injection) у Spring?
Що хоче почути інтерв’юер. Роль контейнера, впровадження через конструктор і чому це допомагає тестуванню.
Зразок відповіді англійською для тренування вголосIn Spring, I do not create my dependencies with new. I declare what a class needs, usually in the constructor, and the container creates the objects, which we call beans, and passes them in. At startup Spring scans the classes, builds a graph of beans and connects them. I prefer constructor injection, because dependencies are explicit and can be final, and in a unit test I can pass a mock directly without starting Spring. Field injection hides dependencies and makes classes harder to test.
What are bean scopes in Spring?
Що таке області видимості (scope) бінів у Spring?
Що хоче почути інтерв’юер. Singleton за замовчуванням і чому стан усередині singleton небезпечний.
Зразок відповіді англійською для тренування вголосThe default scope is singleton: Spring creates one instance per application context and shares it. Prototype creates a new instance every time the bean is requested. In web applications there are also request and session scopes. The most important thing to remember is that singleton beans are shared between threads, so they must not keep mutable request-specific state in fields. If I need per-request data, I pass it as method arguments or use a request-scoped bean.
How does @Transactional work, and what are its pitfalls?
Як працює @Transactional і які в нього підводні камені?
Що хоче почути інтерв’юер. Механізм проксі, проблема виклику всередині того самого класу та правила відкату.
Зразок відповіді англійською для тренування вголосSpring wraps the bean in a proxy. When a method with @Transactional is called from outside, the proxy opens a transaction, calls the real method, and commits or rolls back. One pitfall is self-invocation: if a method calls another transactional method in the same class, the call does not go through the proxy, so the annotation is ignored. Another is that by default Spring rolls back only on unchecked exceptions, not on checked ones, unless I set rollbackFor. I also keep transactions short and avoid remote calls inside them.
What does Spring Boot auto-configuration do?
Що робить автоконфігурація Spring Boot?
Що хоче почути інтерв’юер. Умовна конфігурація та спосіб її перевизначити.
Зразок відповіді англійською для тренування вголосSpring Boot looks at the libraries on the classpath and the properties I set, and configures sensible defaults for me. For example, if it sees a database driver and a connection URL, it creates a DataSource. Each auto-configuration class is guarded by conditions, like "only if this class is present" or "only if I did not define my own bean". That last condition is important, because it means I can always override the default by defining my own bean. When something behaves strangely, I enable the conditions report to see what was applied and why.
How do you handle exceptions in a Spring REST API?
Як ви обробляєте винятки в REST API на Spring?
Що хоче почути інтерв’юер. Централізована обробка та єдиний формат помилок.
Зразок відповіді англійською для тренування вголосI use a class with @RestControllerAdvice and methods annotated with @ExceptionHandler. This way controllers stay clean, and every error is converted to the same JSON format: a status code, a short error code and a message that is safe to show. I map business exceptions to the right HTTP status, for example 404 for a missing resource and 409 for a conflict. I never return stack traces to clients. I log the details with a correlation ID, so support can find the full error in the logs.
Як вимовляти ключові терміни
- bean
- бін
- annotation
- аноте́йшн
- dependency
- діпе́нденсі
- injection
- індже́кшн
- proxy
- про́ксі
- singleton
- сі́нґлтон
Корисні фрази для відповіді
- Under the hood, Spring creates a proxy that…Під капотом Spring створює проксі, який…
- The default behaviour is…, but I can change it by…Типова поведінка —…, але я можу змінити її за допомогою…
- One pitfall I ran into was…Мені трапився такий підводний камінь:…
- In a unit test, I would replace this with a mock.У модульному тесті я б замінив це моком.
- That depends on whether…Це залежить від того, чи…
- I would check the documentation for the exact rule, but the idea is…Точне правило я б перевірив у документації, але ідея така:…
Типові помилки
- Просто перелічувати анотації. Поясніть, що змушує робити фреймворк кожна з них.
- Називати Spring «магією». Так здається, що ви його не розумієте. Кажіть «контейнер» і «проксі», щоб описати, що відбувається.
- Не згадувати тестування. Інтерв’юерам подобається чути, як проєктне рішення впливає на модульні та інтеграційні тести.
- Плутати Spring і Spring Boot. Spring — це фреймворк, а Spring Boot додає автоконфігурацію, стартери та вбудований сервер.
Часті запитання
Що вчити: Spring чи Spring Boot?
Обидва, у такому порядку: спершу основні ідеї Spring (контейнер, біни, проксі), потім те, що додає Spring Boot. Інтерв’юери часто питають про основні ідеї на прикладах із Boot.
Чи потрібно знати Spring Security?
Для бекенд-ролей у більшості компаній — так, на базовому рівні: автентифікація й авторизація, ланцюжок фільтрів і захист кінцевої точки (endpoint). Чесно скажіть, що ви використовували.
Як описувати свій досвід зі Spring?
Назвіть версію, використані модулі (Web, Data, Security) і одну розв’язану проблему. Конкретна проблема переконує більше, ніж перелік анотацій.
Прочитати відповідь — не те саме, що промовити її. Потренуйте кожне запитання вголос, а потім порівняйте зміст і мову власної відповіді.
Спробувати SpeakRole ↗Інші теми в цьому напрямі