-
Spring(3) - Bean등록하는 방법Back-end/Spring 2021. 6. 24. 22:20반응형
이번 강의는 짧게나마 Spring의 핵심인 Beans를 등록하는 방법을 알아보자.
일단 간략하게 Bean이란 무엇인지부터 설명하고 시작하겠다.
Bean은 우리가 사용하는 객체라고 생각하면 된다. 왜 객체라고 하면되지 빈이라고 할까?
Java의 주요 목표는 코드 간의 재사용, 결합도를 줄이는 것이라고 생각한다.
Bean은 의존성 주입으로 결합도를 줄일 수 있고 싱글톤을 이용해 코드를 재사용 할 수 있다는 큰 장점이 있다.
그리고 Bean을 만들때는 몇 가지 규약이 존재한다.
1. 모든 Property들은 private해야한다.
2. getter(값을 읽음), setter(값을 지정) 메소드가 존재해야한다.
3. 접근 제어자는 아래와 같이 설정한다.
- Class : public
- field : private
- constructor : public
- getter/setter : public
4. 특정 패키지에 존재해야한다.
5. 기본 생성자가 존재해야한다.
6. 직렬화가 되어있어야한다.
위의 4가지 규칙을 지키며 기본적인 Bean을 한 번 만들어보자.
public class Hello { private String name; private Printer printer; //기본 생성자 생성. public Hello() { } public Hello(String name, Printer printer) { this.name = name; this.printer = printer; } //set, get 메소드 생성. public void setName(String name) { this.name = name; } public void getName() { return name; } public void setPrinter(Printer printer) { this.printer = printer; } public void getPrinter() { return printer; } }
이렇게 Hello 빈을 만들어 봤다. set으로 값을 지정하고 get으로 값을 얻어 더 많은 메소드를 만들어 낼 수 있다.
그럼 이러한 Bean들은 어떻게 등록을 할까?
요즘은 XML파일을 사용하지 않고 자바코드로 등록한다. 자바코드로 등록하는 2가지 방법이 있다. 하나씩 소개하겠다.
1. @Component Annotation이용
첫 번째로는 Component Annotation을 이용하는 것이다.
이것을 이용하면 Component Scanner라는 놈이 자동적으로 컨테이너 안에서 @Component가 붙은 객체들을 Bean으로 등록해준다. 그리고 @Component안 붙혀도 자동으로 등록되는 것이 있는데 @Controller, @Service, @Repository 3가지 경우가 있다.
아래의 예시는 예전에 XML파일에 직접 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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-4.3.xsd"> </beans>
Bean Configuration File생성.
//constructor injection <bean id="hello" class="myspring.di.annot.Hello"> <constructor-arg index="0" value="${myname}"></constructor-arg> <constructor-arg index="1" ref="${myprinter}"></constructor-arg> </bean> //setter injection <bean id="hello" class="myspring.di.annot.Hello"> <property name="name" value="Spring"></property> <property name="name" ref="Printer"></property> </bean>
Bean주입.
2. @Configuration과 @Bean이용
일단 예시를 보고 설명하겠다.
@Configuration public class SpringConfig { @Bean public MemberService memberService() { return new MemberService(memberRepository()); } @Bean public MemberRepository memberRepository() { return new MemoryMemberRepository(); } }
위의 예시와 같이 @Configuration은 Bean들이 있습니다라고 명시적으로 알려주는 Annotation이다.
그리고 @Bean을 적고 그 안에 넣고 싶은 Bean을 넣으면 된다. 위의 예시는 Service가 Repository를 주입받고있다.
그리고 의존관계 주입이 된 Beans을 컨테이너 내에서 사용 할 수 있다.
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class); MemberService memberService =applicationContext.getBean("memberService", MemberService.class);
ApplicationContext라는 DI컨테이너를 생성해준다.
그리고 getBean메소드를 이용하여 객체를 받아와서 사용한다. 인자는 첫 번째는 대부분 SpringConfig에 설정 되어진 메소드 이름이고 두번째 인자는 사용 클래스.class를 붙혀서 넣으면 된다.
이렇게 Bean이 무엇인지 왜 사용하는지에 대해서 알아보고 Bean을 등록하는 방법까지 알아봤다.
Spring은 공부를 해도해도 너무 깊숙한 영역이라 파고 들기 힘들다. 그러나 진입장벽이 높은 곳은 항상 마지막에
오는 성취감이 장난 아니기 때문에 도전해보고 이 Framework에 대해서 익숙해지고 싶다.
반응형'Back-end > Spring' 카테고리의 다른 글
Spring(6) - Mock, Mockito (0) 2021.08.25 Spring(5) - @Transactional (0) 2021.08.18 Spring(4) - 의존 관계 주입, DI(Dependency Injection) (0) 2021.07.11 Spring(2) - Junit Test과 Spring Test (0) 2021.06.24 Spring(1) - Ioc와 DI컨테이너 작성 (0) 2021.06.24