Home Bean
Post
Cancel

Bean

Bean이란?

IoC 컨테이너에 의해서 생성되고 조립되고, 관리되는 오브젝트

Spring Bean 구성요소

  • class : Bean으로 등록할 java 클래스
  • id : Bean의 고유 식별자
  • scope : Bean을 생성하기 위한 방법(singleton, prototype 등)
  • constructor-arg : Bean 생성시 생성자에 저달할 파라미터
  • property : Bean 생서 시 setter에 전달할 인수
  • 개발자가 직접 제어가 불가능한 외부 라이브러리 또는 설정을 위한 클래스를 Bean으로 등록할 때 @Bean 어노테이션을 활용
  • 메소드와 어노테이션위에서만 @Bean선언가능

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
public class ApplicationConfig {
	@Bean
	public Car car(Engine e) {
		Car c = new Car();
		c.setEngine(e);
		return c;
	}
	
	@Bean
	public Engine engine() {
		return new Engine();
	}
}

위와 같이 Bean을 등록 시켜놓으면 다음과 같이 등록된 Bean을 주입할수 있다.

1
2
3
4
5
6
7
8
9
public class ApplicationContextExam03 {
	public static void main(String[] args) {
		// 클래스를 매개변수로 넣는다.
		ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class);
		
		Car car = ac.getBean(Car.class);
		car.run();
	}
}
This post is licensed under CC BY 4.0 by the author.

annotation

lombok

Comments powered by Disqus.

Trending Tags