웹사이트 검색

스프링 @Bean 주석


직접 호출하여 동일한 클래스의 Spring @Bean 메소드.

스프링 @Bean 예제

아래와 같은 간단한 클래스가 있다고 가정해 보겠습니다.

package com.journaldev.spring;

public class MyDAOBean {

	@Override
	public String toString() {
		return "MyDAOBean"+this.hashCode();
	}
}

다음은 MyDAOBean 클래스에 대한 @Bean 메소드를 정의한 구성 클래스입니다.

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();
		
//Getting Bean by Class
MyDAOBean myDAOBean = context.getBean(MyDAOBean.class);

스프링 빈 이름

@Bean 이름을 지정하고 이를 사용하여 스프링 컨텍스트에서 가져올 수 있습니다. 다음과 같이 정의된 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

스프링 빈 초기화 방법과 파괴 방법을 지정할 수도 있습니다. 이러한 메서드는 각각 Spring Bean이 생성될 때와 컨텍스트가 닫힐 때 호출됩니다.

@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"}, initMethod="init", destroyMethod="destroy")
public MyFileSystemBean getMyFileSystemBean() {
	return new MyFileSystemBean();
}

컨텍스트 새로 고침 메소드를 호출할 때 "init\ 메소드가 호출되고 컨텍스트 close 메소드를 호출할 때 "destroy\ 메소드가 호출된다는 것을 알 수 있습니다.

요약

Spring @Bean 어노테이션은 어노테이션 기반 스프링 애플리케이션에서 널리 사용됩니다.

GitHub 리포지토리에서 전체 스프링 프로젝트를 다운로드할 수 있습니다.