스프링 프레임워크(26) Bean Scanning, 어노테이션, Properties 파일 사용

넙데데맨·2022년 6월 18일
0

Bean scanning을 통한 자동인식 Bean 등록기능

특정 어노테이션이 붙은 클래스를 자동으로 찾아서 Bean으로 등록해주는 방식

  • XML 문서 생성과 관리 쉬움(개발 속도 향상)
  • Bean들 간의 의존 관계를 한눈에 파악할 수 없다.
  • 개발 환경에 적합

XML 단독 사용 특징

  • XML 파일 관리 번거로움
  • 설정파일을 동시 수정하다가 충돌 가능성이 있다.
  • DI에 필요한 setter, 생성자가 코드 내에 반드시 존재해야한다.
  • 운영 환경에 적합

Annotation

Bean 등록 어노테이션

@Component

컴포넌트의 스테레오 타입 <bean> 태그와 동일한 역할

@Repository

영속성을 가지는 속성을 가진 클래스(파일, DB)

@Service

비즈니스 로직 가진 클래스

@Controller

프레젠테이션 레이어에서 사용
웹 어플리케이션에서 요청 응답을 처리하는 클래스

Bean 의존관계 주입 Annotation

@Autowired

  • 정밀 DI가 필요한 경우 유용하다
  • property, setter, 생성자 일반 메소드에 적용 가능
  • Type을 이용한 주입
  • <property> <constructor-arg>와 동일한 역할

@Resource

  • property, setter에 적용가능
  • Name을 이용한 주입

@Value

  • 단순 값 주입 시 사용되는 어노테이션
    @Value("Spring") = <property ~ value="Spring">

@Qualifier

  • @Autowired와 같이 사용됨
  • @Autowired가 타입을 이용한 주입을 하기 때문에
    동일 타입 Bean이 여러 개 존재 시 특정 Bean을 찾기 위해 사용

Component Scan 지원

<context:component-scan>

@Component를 통해 자동으로 Bean 등록하고 @Autowired로 의존관계를 주입받는 어노테이션을 클래스에서 선언해서 사용했을 경우 해당 클래스가 위치한 특정 패키지를 Scan하기 위한 설정이 필요하다
<context:component-scan base-package="myspring.di.annot />"

<context:include-filter><context:exclude-filter>

자동 스캔 대상에 포함시킬 클래스와 포함시키지 않을 클래스 구체적 명시하는 태그

어노테이션 활용

POJO 클래스 작성

StringPrinter.java

@Component("stringPrinter") // id가 stringPrinter인 Bean으로 사용하겠다!
public class StringPrinter implements Printer {
}

Hello.java

package myspring.di.annot;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Hello {
	@Value("Spring")
	private String name;

	@Autowired // Printer
	@Qualifier("stringPrinter") // Printer타입이 2개기 때문에 불러올 클래스 명시해줌 
	private Printer printer;
	List<String> names;

	public Hello() {

	}

	public Hello(String name, Printer printer) {
		this.name = name;
		this.printer = printer;
	}
	/*
	 * Setter가 없어도 인젝션 가능
	 * public void setNames(List<String> names) { this.names = names; }
	 * 
	 * public void setName(String name) { this.name = name; }
	 *
	 * public void setPrinter(Printer printer) { this.printer = printer; }
	 */

	public List<String> getNames() {
		return names;
	}

	public String sayHello() {
		// TODO Auto-generated method stub
		return "Hello " + name;
	}

	public void print() {
		this.printer.print(sayHello());
	}

}

annot.xml

<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 http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

	<context:component-scan base-package="myspring.di.annot"></context:component-scan>
</beans>

HelloBeanAnnotTest.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:config/annot.xml")
public class HelloBeanAnnotTest {
	@Autowired
	ApplicationContext context;
	
	@Test
	public void test() {
		Hello hello = context.getBean("hello",Hello.class);
		assertEquals("Hello Spring", hello.sayHello());
	}
}

Properties 파일 및 Bean 설정파일 작성

value.properties

myname=Spring
myprinter=printer
value1=AOP
value2=Spring
value3=DI
printer1=stringPrinter
printer2=consolePrinter

Hello.java

public class Hello {
	@Value("${myname}") // value.properties 활용위해 $ 사용
	private String name;
	@Resource(name="${printer1}") // value.properties 활용 시 사용
	private Printer printer;
}

annot.xml

<!-- properties 파일 사용을 위해 추가해야함 -->
<context:property-placeholder location="classpath:config/value.properties"/>

정리

  • XML 단독
  • XML 빈 스캐닝 혼용
  • Bean 등록 / 의존관계 설정 어노테이션
  • Properties 파일 사용법
profile
차근차근

0개의 댓글