봄 @Bean 주석은 메서드에 적용되어 해당 메서드가 Spring 컨텍스트에서 관리되는 빈을 반환함을 지정합니다. Spring Bean 주석은 일반적으로 Configuration 클래스의 메서드에서 선언됩니다. 이 경우 빈 메서드는 직접 호출하여 동일한 클래스의 다른 @Bean 메서드를 참조할 수 있습니다.
Spring @Bean 예제
다음과 같은 간단한 클래스가 있다고 가정해 봅시다.
package com.journaldev.spring;
public class MyDAOBean {
@Override
public String toString() {
return "MyDAOBean"+this.hashCode();
}
}
여기에는 MyDAOBean
클래스에 대한 @Bean 메서드를 정의한 Configuration 클래스가 있습니다.
package com.journaldev.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyAppConfiguration {
@Bean
public MyDAOBean getMyDAOBean() {
return new MyDAOBean();
}
}
아래 코드 스니펫을 사용하여 Spring 컨텍스트에서 MyDAOBean
빈을 가져올 수 있습니다.
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
//클래스별로 빈 얻기
MyDAOBean myDAOBean = context.getBean(MyDAOBean.class);
Spring Bean 이름
@Bean 이름을 지정하고 해당 이름을 사용하여 spring 컨텍스트에서 빈을 가져올 수 있습니다. 예를 들어 MyFileSystemBean
클래스를 다음과 같이 정의했다고 가정해 봅시다:
package com.journaldev.spring;
public class MyFileSystemBean {
@Override
public String toString() {
return "MyFileSystemBean"+this.hashCode();
}
public void init() {
System.out.println("init method called");
}
public void destroy() {
System.out.println("destroy method called");
}
}
이제 구성 클래스에 @Bean 메서드를 정의합니다:
@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"})
public MyFileSystemBean getMyFileSystemBean() {
return new MyFileSystemBean();
}
우리는 빈 이름을 사용하여 이 빈을 컨텍스트에서 가져올 수 있습니다.
MyFileSystemBean myFileSystemBean = (MyFileSystemBean) context.getBean("getMyFileSystemBean");
MyFileSystemBean myFileSystemBean1 = (MyFileSystemBean) context.getBean("MyFileSystemBean");
Spring @Bean initMethod 및 destroyMethod
또한 스프링 빈 초기화 메서드 및 소멸 메서드를 지정할 수 있습니다. 이 메서드들은 스프링 빈이 생성될 때와 컨텍스트가 닫힐 때 각각 호출됩니다.
@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"}, initMethod="init", destroyMethod="destroy")
public MyFileSystemBean getMyFileSystemBean() {
return new MyFileSystemBean();
}
우리는 “init” 메서드가 컨텍스트 refresh
메서드를 호출할 때 호출되고 “destroy” 메서드가 컨텍스트 close
메서드를 호출할 때 호출되는 것을 알 수 있습니다.
요약
Spring @Bean 어노테이션은 주석 기반의 스프링 애플리케이션에서 널리 사용됩니다.
당신은 우리의 GitHub Repository에서 완전한 스프링 프로젝트를 다운로드할 수 있습니다.
Source:
https://www.digitalocean.com/community/tutorials/spring-bean-annotation