티스토리 뷰

프로그래밍/Web

Spring Bean 생성 및 사용

국윤창 2018. 7. 19. 15:32

Bean

Bean은 Spring Bean Container에 존재하는 객체를 말한다. Bean Container는 의존성 주입을 통해 Bean 객체를 사용할 수 있도록 해준다. Bean은 보통 싱글턴으로 존재한다.

XML Configuration

Java 코드를 이용한 Context 설정이 나오기 전 사용하던 방법이다. applicationContext.xml이라는 파일을 src/main/resources 폴더에 추가시킨 후 bean을 등록한다. 아래 코드처럼 작성할 수 있다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<bean id="userBean" class="com.example.diexam01.UserBean"></bean>
	<bean id="e" class="com.example.diexam01.Engine"></bean>
	<bean id="c" class="com.example.diexam01.Car">
		<property name="engine" ref="e"></property>
	</bean>
</beans>

beans 태그 아래에 bean 태그가 여러개 있는 것을 볼 수 있다. bean 태그의 id가 bean의 이름이 되고 class에 어떤 클래스를 bean으로 만들지 패키지명을 포함하여 적으면 된다. 

bean 태그 아래에 property 태그를 보면, engine이라는 이름의 property는 e를 참조하라고 써있다. 이 부분은, e라는 이름으로 등록된 bean을 c라는 이름의 bean 내부의 getEngine, setEngine이라는 함수를 통해 사용하겠다(DI, 의존성주입 하겠다)는 이야기이다. 

public class Engine {
	public Engine() {
		System.out.println("Engine 생성자");
	}
	
	public void exec() {
		System.out.println("엔진이 동작합니다.");
	}
}

public class Car {
	private Engine v8;
	
	public Car() {
		System.out.println("Car 생성자");
	}
	
	public void setEngine(Engine e) {
		v8 = e;
	}
	
	public void run() {
		System.out.println("엔진을 이용하여 달립니다.");
		v8.exec();
	}
}

이후 아래 코드처럼 ApplicationContext를 통해 Car 객체('c'라는 이름의 Bean)를 가져와서 사용해보면, 직접 Engine 객체를 Car 내부의 v8에 등록하지 않았는데 정상적으로 실행이 되는 것을 알 수 있다.

public class ApplicationContextExam02 {
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		Car car = (Car)ac.getBean("c");
		car.run();
	}
}

Java Configuration

@Configuration이라는 애노테이션을 이용하여 XML 대신 Java로 Bean을 생성할 수 있다. 아래처럼 Config 클래스를 만들어서 그 위에 @Configuration 어노테이션을 달자. 그 후 Bean으로 사용할 객체를 반환하는 메소드를 만들고, @Bean이라는 어노테이션을 달면 반환된 객체가 Bean Container에 등록된다.

@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();
	}
}

사용할 때는 아래처럼 ClassPathXmlApplicationContext 대신 AnnotationConfigApplicationContext 객체를 생성하여 Bean을 초기화 할 수 있다.

public class ApplicationContextExam03 {
	public static void main(String[] args) {
		// 클래스를 매개변수로 넣는다.
		ApplicationContext ac = new AnnotationConfigApplicationContext(ApplicationConfig.class);
		
		Car car = ac.getBean(Car.class);
		car.run();
	}
}

@ComponentScan

Spring 2.0 이후부터 stereo type이 등장하면서 더 쉽게 Bean을 등록할 수 있게 되었다. Config 클래스에 @Configuration 어노테이션과 @ComponentScan 어노테이션을 같이 등록하면, 패키지 내의 @Component, @Controller, @Service, @Repository로 등록된 클래스를 Classpath Scanning 타임에 Bean Container에 등록시켜 준다. 아래처럼 Config 클래스와 Bean으로 등록할 클래스를 정의할 수 있다.

@Configuration
@ComponentScan("com.example.diexam01")
public class ApplicationConfig2 {
	
}

@Component
public class Car {
	@Autowired
	private Engine v8;
	
	public Car() {
		System.out.println("Car 생성자");
	}
	
	public void run() {
		System.out.println("엔진을 이용하여 달립니다.");
		v8.exec();
	}
}

@Component
public class Engine {
	public Engine() {
		System.out.println("Engine 생성자");
	}
	
	public void exec() {
		System.out.println("엔진이 동작합니다.");
	}
}

@Autowired 어노테이션을 통해 이미 Bean으로 등록된 인스턴스를 런타임에 의존성 주입할 수 있다.

'프로그래밍 > Web' 카테고리의 다른 글

Spring MVC와 Dispatcher Servlet  (0) 2018.07.19
Spring JDBC  (0) 2018.07.19
java properties 파일 사용하기  (0) 2018.07.18
Javascript 동적 UI 만들기  (0) 2018.07.17
Eclipse Maven 웹 프로젝트 설정  (0) 2018.07.12
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함