[Spring] component 태그 활용 의존성 주입
2023. 10. 24. 20:19
728x90
** 전과 같이 MyRoom (main) + Tape + TapeReader 클래스 활용.
- MyRoom main --> component-scan 컨테이너 구성
- Tape --> @Component로 bean으로 등록 / @Value 애너테이션을 생성자로 이동
- TapeReader --> @ Component 활용 bean 등록 / setter 메소드 삭제
1. Component scan 태그
1) component-scan-config.xml 파일 생성
- 이전과 동일...
- 해당 링크에서 xml 엘리먼트 가지고오기
- Annotation 기반 설정 구성을 하기 위한 엘리먼트를 추가해야 함 : xmlns:context attribute를 추가했기 때문에 애너테이션 작성이 가능함. (xmlns:context="http://www.springframework.org/schema/context")
- xml 파일에 별도의 <bean> 을 작성하지 않고도 컨테이너에 bean으로 등록할 수가 있다!!! 오엥!? 어떻게? 점점 xml 파일과의 의존성이 줄어들고 있다.
- >> component 태그를 모두 스캔하게 하는 context:component-scan 활용하기
- base-package를 설정해주기 : 기본 패키지 주소
<?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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="dev.spring" />
</beans>
2) MyRoom 클래스에서 annotation 기반 컨테이너 구성.
=> ApplicationContext context = new ClassPathXmlApplicationContext("component-scan-config.xml");
3) @ Component 애너테이션을 클래스에 달아 해당 클래스를 bean으로 등록하여 스캐닝 대상에 포함.
- setter 주입은 없다. 삭제하기
- @Value 태그는 생성자로 이동.
- 생성자가 1개만 존재할 경우 스프링 4.3 이후부터는 @Autowired 태그가 없어도 적용됨. (As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean defines only one constructor to begin with.)
- ref link: https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired.html#beans-autowired-annotation-constructor-resolution
*Tape
package dev.spring;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component // 해당 클래스를 bean으로 등록, 스캐닝 대상에 포함시킴.
public class Tape {
private String name; // 필드 기반 기본 값 지정
private boolean isWorked; // true, false로 바꿔보기
// 기본 생성자 없애기 or @Autowired를 직접 원하는 생성자에 명시하기.
public Tape(@Value("아일랜드") String name, @Value("true") boolean isWorked) {
super();
this.name = name;
this.isWorked = isWorked;
}
public String getName() {
return name;
}
public boolean isWorked() {
return isWorked;
}
}
*TapeReader : 똑같이 setter 메소드 삭제 / @Component 애너테이션.
package dev.spring;
import org.springframework.stereotype.Component;
@Component
public class TapeReader {
private Tape tape;
public TapeReader(Tape tape) {
this.tape = tape;
}
public void test() {
if (tape.isWorked()) {
System.out.println(tape.getName() + " 정상 동작합니다");
} else {
System.out.println(tape.getName() + " 사기 당했습니다");
}
}
@Override
public String toString() {
return "TapeReader 입니다.";
}
}
출력문 순서 !
- TapeReader 입니다. // Tape 생성자 생성과 동시에 value 값이 매겨지고 TapeReader toString() 메서드 실행
- 아일랜드 정상 동작합니다. // TapeReader test() 메서드 실행
결론 : 점점 미친듯이 편리하게 설정이 되고 있다. 귀차니즘의 힘이란... 매우 신기한 효율성의 세계.
728x90
'Programming > Spring, SpringBoot' 카테고리의 다른 글
JPA (Java Persistence API) 기초/설정 (0) | 2023.10.25 |
---|---|
[Spring] Spring MVC web.xml 설정 (0) | 2023.10.25 |
[Spring] Annotation 기반 컨테이너 구성 (0) | 2023.10.24 |
[Spring] XML 기반 컨테이너 구성 (0) | 2023.10.24 |
[Spring] pom.xml 작성 (0) | 2023.10.24 |