포스코x코딩온 웹 풀스택 양성과정

[포스코x코딩온] 웹 풀스택 과정 18주차 회고 | Spring Bean

Codult 2024. 4. 18. 23:35
728x90

Bean

Spring IoC 컨테이너가 관리하는 Java 객체이다.

  • 의존성 관리가 용이하다.
  • 동일한 객체를 여러 번 만들지 않고, 하나를 만들어 재사용한다는 점에서, 메모리를 절약할 수 있다.

Bean 등록방법

방법 1) @Component 이용

  • 클래스 선언부 위에 @Component 어노테이션.

방법 2) 자바 설정 클래스 직접 만들기

  • 설정 클래스를 만들고 @Configuration 어노테이션 후, 해당 크래스 안의 메소드에 @Bean 어노테이션.
record Person(String name, int age) {} // record: getter, setter, 생성자 등을 자동으로 생성
record Address(String address, int postcode) {}
@Configuration	// 빈 정의를 포함하는 클래스
public class HelloWorldConfig{
	@Bean
    public String name() { return "myname";}
    
    @Bean
    public Person person() { return new Person("James", 20);}
    
    @Bean
    // 위에서 정의한 빈을 바로 사용할 수도 있다.
    public Person person2() { return new Person(name(), 22;}
    
    @Bean(name="myAddress")	// 빈 이름 변경할 수 있다.
    public Address address() { return new Address("seoul", 12345);}
    
    @Bean
    @Primary
    // @Primary: Bean 불러올 때, 우선순위를 갖는다.
    public Address2 address() { return new Address("busan", 12345);}
}

Configuration에서 Bean 가져오기

AnnotationConfigApplicationContext()으로 가져오려는 빈이 정의되어 있는 Config를 불러온다.
getBean()으로 context에서 빈을 가져온다.

public class HelloWorld {

	var context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
    
    // Bean 이름으로 불러온다.
    System.out.println(context.getBean("name")); // myname
    System.out.println(context.getBean("person")); // Person[name=James, age=20]
    System.out.println(context.getBean("myAddress")); // Address[address=seoul, postcode=12345]
    // 2개 이상의 값을 가져올 때, @Primary로 어노테이션 한 값이 온다.
    System.out.println(context.getBean(Address.class)); // Address[address=busan, postcode=12345]
    
}
728x90