JAVA_IIBRARY Telegram 1814
Вопрос из Java-собеседования (сценарный):

Ты используешь @Autowired для field injection в Spring-проекте. Это просто и работает.

@Component
public class UserService {

@Autowired
private UserRepository userRepository;
}


Тимлид просит тебя отрефакторить это, так как field injection часто считается плохой практикой.

Подумай о минусах field injection:

→ Visibility: скрывает обязательные зависимости класса.
→ Testability: усложняет unit-тестирование, часто требует рефлексии.
→ Runtime Issues: может привести к NullPointerException, если зависимость отсутствует.
→ Design: поощряет классы с чрезмерной ответственностью (нарушение SRP).

Какой рекомендуемый вариант?

→ Constructor Injection.

Зависимости явно передаются при создании объекта, делая их обязательными.

@Component
public class UserService {
private final UserRepository userRepo; // final!

public UserService(UserRepository userRepo) {
this.userRepo = userRepo;
}
}


Почему Constructor Injection лучше?

→ Explicit: явно показывает, что нужно классу для работы.
→ Guaranteed: приложение не поднимется, если зависимости нет.
→ Immutable: final-поля безопаснее и дружелюбнее к многопоточности.
→ Testable: легко замокать и прокинуть зависимости в тестах.

Это приводит к более надежному и поддерживаемому коду.

👉 Java Portal
Please open Telegram to view this post
VIEW IN TELEGRAM
10👍4💊1



tgoop.com/Java_Iibrary/1814
Create:
Last Update:

Вопрос из Java-собеседования (сценарный):

Ты используешь @Autowired для field injection в Spring-проекте. Это просто и работает.

@Component
public class UserService {

@Autowired
private UserRepository userRepository;
}


Тимлид просит тебя отрефакторить это, так как field injection часто считается плохой практикой.

Подумай о минусах field injection:

→ Visibility: скрывает обязательные зависимости класса.
→ Testability: усложняет unit-тестирование, часто требует рефлексии.
→ Runtime Issues: может привести к NullPointerException, если зависимость отсутствует.
→ Design: поощряет классы с чрезмерной ответственностью (нарушение SRP).

Какой рекомендуемый вариант?

→ Constructor Injection.

Зависимости явно передаются при создании объекта, делая их обязательными.

@Component
public class UserService {
private final UserRepository userRepo; // final!

public UserService(UserRepository userRepo) {
this.userRepo = userRepo;
}
}


Почему Constructor Injection лучше?

→ Explicit: явно показывает, что нужно классу для работы.
→ Guaranteed: приложение не поднимется, если зависимости нет.
→ Immutable: final-поля безопаснее и дружелюбнее к многопоточности.
→ Testable: легко замокать и прокинуть зависимости в тестах.

Это приводит к более надежному и поддерживаемому коду.

👉 Java Portal

BY Java Portal | Программирование




Share with your friend now:
tgoop.com/Java_Iibrary/1814

View MORE
Open in Telegram


Telegram News

Date: |

bank east asia october 20 kowloon 6How to manage your Telegram channel? During a meeting with the president of the Supreme Electoral Court (TSE) on June 6, Telegram's Vice President Ilya Perekopsky announced the initiatives. According to the executive, Brazil is the first country in the world where Telegram is introducing the features, which could be expanded to other countries facing threats to democracy through the dissemination of false content. More>> The creator of the channel becomes its administrator by default. If you need help managing your channel, you can add more administrators from your subscriber base. You can provide each admin with limited or full rights to manage the channel. For example, you can allow an administrator to publish and edit content while withholding the right to add new subscribers.
from us


Telegram Java Portal | Программирование
FROM American