스프링 빈(Bean) 이란?

2023. 11. 5. 02:51백엔드/Spring Boot

Spring Bean 

: Spring Bean은 스프링 컨테이너가 관리하는 자바 객체로 컨테이너에 의해 생명주기(Lifecycle)가 관리된다. 

 

Bean의 생명주기(Lifecycle) 

: Bean 객체가 생성되고 초기화되며 소멸되는 일련의 단계를 의미한다. 

 

생명 주기 단계 

  1. 스프링 컨테이너 생성
  2. Bean 등록
  3. 의존성 주입
  4. 초기화
  5. 사용
  6. 소멸
  7. 스프링 종료

 


 

 

 

생명 주기 단계 - Bean 등록 

1. @Configuration + @Bean 조합을 이용하여 직접 등록 

@Configuration
public class AppConfig {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }

    @Bean
    public AnotherBean anotherBean() {
        // 의존성 주입
        return new AnotherBean(myBean());
    }
}

 

 

2. 컴포넌트 스캔을 활용하여 자동으로 등록 

@Component, @Service, @Repository, @Controller 어노테이션을 이용하여 bean을 자동으로 등록할 수 있다. 

(@Service, @Repository, @Controller 어노테이션에는 @Component 어노테이션이 포함되어 있다. )

 

1) @Component 

// @Component를 명시하여 빈에 등록하기 위해 ComponentScan 어노테이션을 사용 
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
    // AppConfig의 설정
}

@Component // 해당 어노테이션을 이용하여 MyComponent 클랙스를 빈으로 등록
public class MyComponent {
    // Bean의 내용
}

 

2) @Service

@Service
public class MyService {
    // 서비스 Bean의 내용
}

// Service.java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}

 

3) @Repository

@Repository
public class MyRepository {
    // 데이터 액세스 Bean의 내용
}

// Repository.java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}

4) @Controller

@Controller
public class MyController {
    // 컨트롤러 Bean의 내용
}

//Controller.java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}

 

 

 

 

생명 주기 단계 - 의존성 주입 

Bean 등록 후 DI를 주입하기 위해 @Autowired 어노테이션을 사용한다. 

@Autowired 어노테이션은 가장 간편하고 일반적으로 사용되는 방법으로 이 어노테이션을 사용하면 Spring 컨테이너는 필드, 생성자, 메소드에 자동으로 빈을 주입하여 코드의 가독성을 향상시키고, 의존성 주입 관련 코드가 간결하게 표현될 수 있게 한다. 

 

1. 필드 주입

@Autowired
private DemoService demoService;

 

2. 생성자 주입

private final DemoService demoService;

@Autowired
public DemoController(DemoService demoService) {
    this.demoService = demoService;
}

 

3. 메소드 주입

@Autowired
public void setMyService(DemoService demoService) {
    this.demoService = demoService;
}