Sobes.tech
Junior — Middle

Обеспечивается ли создание одного и того же экземпляра компонента при использовании аннотации @Autowired в разных частях класса, помеченного @Component?

sobes.tech AI

Answer from AI

Yes, when using the @Autowired annotation in the Spring Framework for dependency injection into a class marked as @Component, by default, a single instance of the component (Singleton scope) is created. This means that in different parts of the class where the same component is injected via @Autowired, the same instance will be used.

For example:

@Component
public class MyService {
    @Autowired
    private MyRepository repo1;

    @Autowired
    private MyRepository repo2;

    public void doSomething() {
        // repo1 and repo2 refer to the same instance of MyRepository
    }
}

Thus, Spring manages the lifecycle of components and ensures the reuse of a single instance unless otherwise specified (for example, using the @Scope annotation).

Обеспечивается ли создание одного и того же… - sobes.tech