Over the limit

Spring Bean 스프링 빈 본문

Framework/Spring

Spring Bean 스프링 빈

ellapk 2022. 5. 20. 07:43

빈(Bean)

  • 애플리케이션의 핵심을 이루는 객체
  • Spring Ioc(Inversion of Control) 컨테이너에 의해 인스턴스화, 관리, 생성 된다.
  • XML 파일에 의해 생성되며 컨테이너는 이 데이터를 통해 Bean 생성, Bean Life Cycle, Bean Dependency등을 알 수 있다.
  • 애플리케이션의 객체가 지정되면, 해당 객체는 getBean() 메서드를 통해 가져올 수 있다.

 

 

+) XML 파일?

<!-- A simple bean definition -->
<bean id="..." class="..."></bean>

<!-- A bean definition with scope-->
<bean id="..." class="..." scope="singleton"></bean>

<!-- A bean definition with property -->
<bean id="..." class="...">
	<property name="message" value="Hello World!"/>
</bean>

이런 식으로 configuration을 지시하는 파일

 

 

 

 

 

 

빈 등록 방법

1. 자바 어노테이션 사용

 

Bean을 등록하기 위해서는 @Component Annotation을 사용한다. @Component Annotation이 등록되어 있는 경우에는 Spring이 Annotation을 확인하고 자체적으로 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 "";

}

 

상단에 코드를 보면, @Component Annotation으로 인하여 Spring은 해당 Controller를 Bean으로 등록한다.

 

한번 더 이해하기 위해 Bean에 등록된 객체와 그렇지 않은 객체를 비교해보자.

package main;
public class repo1 implements repo{
	private int a;
	public int getA() {
		return a;
	}
	public void setA(int a) {
		this.a = a;
	}
	public void pr()
	{
		System.out.println(a);
	}
}

>Bean에 등록이 안된 객체

 

 

@Service
public class repo2 implements repo{
	private int a;
	public int getA() {
		return a;
	}
	public void setA(int a) {
		this.a = a;
	}
	public void pr()
	{
		System.out.println(a);
	}
}

>Bean에 등록된 객체

 

 

 

 

 

 

2. Bean Configuration File에 직접 Bean 등록하는 방법

@Configuration과 @Bean Annotation 을 이용하여 Bean을 등록할 수 있다. 아래의 예제와 같이 @Configuration을 이용하면 Spring Project 에서의 Configuration 역할을 하는 Class를 지정할 수 있으며, 해당 File 하위 Bean 으로 등록하고자 하는 Class에 @Bean Annotation을 사용해주면 된다.

// Hello.java
@Configuration
public class HelloConfiguration {
    @Bean
    public HelloController sampleController() {
        return new SampleController;
    }
}

 

 

 

+) Bean을 등록하는 이유?

인터페이스로 구현된 Repository 클래스가 다른 클래스로 변경될 때 간단하게 Configuration의 리턴 클래스 객체만을 수정해주면 된다는 점이 있다.

 

 

 

 

 

[Spring] Spring Bean의 개념과 Bean Scope 종류 - Heee's Development Blog (gmlwjd9405.github.io)

스프링 빈(Spring Bean)이란? 개념 정리 - Easy is Perfect (melonicedlatte.com)