> Java > java지도 시간 > 본문

스프링 부트의 의존성 주입: 막 뒤의 마법사

DDD
풀어 주다: 2024-09-19 02:19:02
원래의
202명이 탐색했습니다.

Dependency Injection in Spring Boot: The Wizard Behind the Curtain

Spring Boot의 종속성 주입: 커튼 뒤의 마법사

Spring Boot가 필요한 것이 무엇인지 알고 은쟁반에 담아 건네주는 마법의 집사 같은 느낌을 받은 적이 있나요? 이것이 기본적으로 의존성 주입입니다(DI). 아마도 당신은 궁금해하지 않고 DI를 100번 이상 사용했을 것입니다. Spring은 무엇을 언제 주입해야 하는지 도대체 어떻게 알까요?

당신도 그렇게 생각하신다면, 참여를 환영합니다! 우리는 Spring Boot의 DI가 Bean, @Autowired 및 Bean 라이프사이클을 관리하는 방법부터 시작하여 생성부터 소멸까지 마법처럼 작동하는 방식에 대한 재미있는 비하인드 스토리를 살펴보겠습니다. 이 블로그가 끝날 무렵에는 새로 발견한 DI 지식을 전문가처럼 활용하게 될 것입니다.


의존성 주입이란 무엇인가요? 그리고 왜 관심을 가져야 합니까?

일반인의 관점에서 보면 의존성 주입은 식료품을 직접 사러 나가지 않고 집까지 배달받는 것과 같습니다. 이는 종속성(빈)을 "주입"하는 책임을 Spring에 위임하여 수동으로 객체를 생성하거나 수명 주기에 대해 걱정할 필요가 없도록 하는 것입니다.

당신이 분주한 주방을 운영하는 셰프라고 상상해 보세요(지원서). 필요할 때마다 달려가 계란, 우유, 설탕을 집어들 시간이 없습니다. 누군가(가령 봄)가 마법처럼 필요한 모든 것을 필요할 때 정확하게 배달해 준다면 얼마나 좋을까요?

이것이 바로 Spring DI가 수행하는 작업입니다. 필요한 모든 재료(빈)를 찾아서 손가락 하나 까딱하지 않고도 코드에 주입합니다. 꽤 깔끔하죠?


봄 컨테이너의 마법: 나만의 집사

자, 여기서 마법이 일어납니다. SpringApplication.run()을 사용하여 Spring Boot 앱을 실행하면 Spring은 ApplicationContext를 부트스트랩합니다. 이를 집사의 사용 설명서라고 생각하세요. 무엇을 언제 가져올지 정확히 알고 있습니다.

단계별로 분석해 보겠습니다.

  1. 컨테이너 초기화: SpringApplication.run()을 실행하면 Spring 컨테이너(일명 ApplicationContext)가 실행됩니다. 이는 모든 것이 준비되어 있는 가상 레스토랑의 문을 여는 것과 같습니다.

  2. Bean 생성: 컨테이너는 코드에서 @Component, @Service, @Repository 또는 @Controller와 같은 주석을 검색합니다. 이들 각각은 Spring이 관리하는 객체인 bean이 됩니다. 밀가루, 설탕, 계란 등 주방의 필수 재료라고 생각하세요.

  3. 구출을 위한 BeanFactory: Spring Boot는 BeanFactory를 사용하여 이러한 Bean을 생성하고 관리합니다. 이 공장에서는 원두를 언제, 어떻게 만드는지 정확히 알고 있어 필요할 때 사용할 수 있도록 보장합니다.

  4. 종속성 주입: Bean이 준비되면 Spring은 @Autowired로 표시된 위치에 빈을 주입합니다. 이는 커피를 만드는 것뿐만 아니라 필요한 곳에 정확한 카운터까지 전달하는 바리스타를 갖는 것과 같습니다. 그것에 대해 생각할 필요도 없습니다. 모든 것이 나타납니다.


@Autowired는 어떻게 작동하나요? 콩의 셜록홈즈

아, @Autowired 주석 좋네요. Spring이 종속성을 주입할 위치를 마술처럼 어떻게 아는지 궁금한 적이 있습니까? 이는 레지스트리에 있는 올바른 빈과 사용자의 요구 사항을 일치시키는 탐정과 같습니다.

작동 방식은 다음과 같습니다.

  • 타입 매칭: Spring이 @Autowired를 보면 컨테이너에서 동일한 타입의 빈을 찾습니다. 당신이 커피콩(CoffeeService 클래스)을 주문했다고 상상해 보세요. Spring은 자신의 Bean 저장소를 보고 "아, 나 이거 가져왔어!"라고 말합니다. 주사를 놔드리겠습니다.”

  • 예선: 그런데 같은 종류의 원두가 여러 개 있다면 어떨까요? 이 경우 Spring은 "NoUniqueBeanDefinitionException"과 같은 예외를 던질 수 있습니다. 하지만 걱정하지 마세요. @Qualifier를 사용하여 주입할 빈을 지정하면 Spring을 진정시킬 수 있습니다.

@Autowired
@Qualifier("espressoBean")
private CoffeeService coffeeService;
로그인 후 복사
  • 생성자 주입(가장 좋은 방법): 요즘에는 생성자 주입이 가장 인기가 높습니다. 이는 빈을 불변으로 만들 뿐만 아니라 테스트도 쉽게 만듭니다. 방법은 다음과 같습니다.
public class CoffeeShop {

    private final CoffeeService coffeeService;

    @Autowired
    public CoffeeShop(CoffeeService coffeeService) {
        this.coffeeService = coffeeService;
    }
}
로그인 후 복사

Spring은 자동 조종 장치로 빈을 생성자에 주입합니다. 짜잔, 이제 잘 진행됩니다!


The Lifecycle of a Spring Bean: From Birth to Retirement Party

Beans in Spring Boot aren’t just objects. They have full-fledged lives, complete with an origin story, a fulfilling career, and an eventual retirement. Let’s follow the lifecycle of a bean:

  1. Instantiation (Birth): First, Spring creates an instance of the bean. This is like the bean’s birth. Spring goes, "Here you go, little guy!" and passes it into the container.

  2. Dependency Injection: After creating the bean, Spring populates it with dependencies (like ingredients in a cake recipe). This is where @Autowired comes into play. Your bean gets everything it needs to work properly.

  3. Post-Initialization: If you have methods annotated with @PostConstruct, Spring calls those after it injects the dependencies. It’s like giving the bean a fresh coat of paint before it goes to work.

  4. Ready for Action: Now your bean is alive and kicking. It’s ready to take on the world!

  5. Pre-Destruction (Retirement): When the application shuts down, Spring calls @PreDestroy methods to give the bean a graceful exit. This is the bean's retirement party, where it cleans up its resources.

  6. Bean Destruction: Finally, the bean is destroyed. Time to rest in peace.

Here’s how you can track these lifecycle events in code:

@Component
public class CoffeeBean {

    @PostConstruct
    public void onStart() {
        System.out.println("Bean is ready to brew some coffee!");
    }

    @PreDestroy
    public void onEnd() {
        System.out.println("Bean is retiring. Goodbye, world!");
    }
}
로그인 후 복사

Bean Scopes: How Long Does the Magic Last?

Not all beans have the same life expectancy. Spring Boot allows you to define different scopes for beans—basically how long they live. The two most common ones are:

  • Singleton (the Default): There’s only one instance of the bean, shared across the entire application. It’s like having one espresso machine for the whole coffee shop.

  • Prototype: A new instance of the bean is created every time it’s needed. Imagine having a fresh espresso machine for every single order. It’s resource-heavy, but sometimes necessary.

@Component
@Scope("prototype")
public class LatteMachine {
    // This bean is made fresh for every use
}
로그인 후 복사

SpringApplication.run(): The Grandmaster of DI

Alright, let’s talk about what happens when you run your Spring Boot app using SpringApplication.run(). This method is the grandmaster that kicks off the whole DI process.

  1. Start the Application Context: Spring fires up the ApplicationContext, where all beans live.
  2. Scan for Beans: Spring scans your code for beans and registers them.
  3. Inject Dependencies: Once the beans are ready, Spring starts injecting them wherever @Autowired is used.
  4. Launch the Application: Once everything is in place, the application goes live. Magic complete.

Real-Life Analogy: DI in a Coffee Shop

Think of your Spring Boot application as a coffee shop. You’re the owner, and the beans are your ingredients: coffee, milk, sugar, etc. Instead of running around managing these ingredients yourself, you’ve got a barista (the Spring container) who fetches everything and delivers it exactly where it’s needed.

All you have to do is give the orders (set up your @Autowired fields), and the barista handles the rest—perfectly brewing that dependency-filled cup of coffee for your customers (application).


Wrapping It Up: DI Is Your Superpower

At the end of the day, Dependency Injection is what makes Spring Boot such a powerful framework. It simplifies your life, manages your beans, and ensures your code is easy to maintain and extend.

Now that you’ve peeked behind the curtain, you’ve got a superpower that many developers take for granted. So go ahead—start using DI like the wizard you now are. And the next time you see @Autowired, you’ll know exactly what’s going on under the hood.


I hope this blog gave you a deeper understanding of Spring Boot DI and left you with a smile. Now go inject some beans and show your friends how it's done!


How’s that for a blog that’s fun, informative, and easy to understand? Let me know if you'd like any more tweaks!

위 내용은 스프링 부트의 의존성 주입: 막 뒤의 마법사의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!