Component Scanning
- config.txt로 공통으로 사용하는 클래스, 객체를 관리할 때 사용한다면, component scanning은 별도로 클래스를 관리할 때 사용.
package com.fastcampus.ch3.diCopy3;
import com.google.common.reflect.ClassPath;
import org.springframework.cglib.core.ClassInfo;
import org.springframework.util.StringUtils;
import org.springframework.stereotype.Component;
import java.awt.*;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
@Component class Car{ }
@Component class sportCar extends Car{}
@Component class Truck extends Car{}
class Engine{}
class AppContext{
Map map;
AppContext() {
map = new HashMap();
doComponentScan();
}
private void doComponentScan() {
try {
// 1. 패키지 내의 클래스 목록을 가져온다.
// 2. 반복문으로 클래스를 하나씩 읽어와서 @Component이 붙어 있는지 확인
// 3. @Component가 붙어 있으면 객체를 생성해서 map에 저장
ClassLoader classLoader = AppContext.class.getClassLoader();
ClassPath classPath = ClassPath.from(classLoader);
Set<ClassPath.ClassInfo> set = classPath.getTopLevelClasses("com.fastcampus.ch3.diCopy3");
for(ClassPath.ClassInfo classInfo : set) {
Class clazz = classInfo.load();
Component component = (Component)clazz.getAnnotation(Component.class);
if(component!=null){
String id = StringUtils.uncapitalize(classInfo.getSimpleName());
map.put(id, clazz.newInstance());
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
Object getBean(String key){return map.get(key);}
Object getBean(Class clazz){ //byname
for (Object obj: map.values()){
if(clazz.isInstance(obj)){
return obj;
}
}
return null;
}
}
public class main3 {
public static void main(String[] args) throws Exception {
AppContext ac = new AppContext();
Car car = (Car)ac.getBean( "car");
Car car2 = (Car)ac.getBean(Car.class);
Engine engine = (Engine)ac.getBean("engine");
System.out.println("car = " + car);
System.out.println("car2 = " + car2);
System.out.println("engine = " + engine);
}
}
내용
- @Component를 통해서 컴포넌트로 등록한 클래스들을 찾기 위해 doComponentScan()이라는 메소드를 사용
- doComponentScan()
- 패키지 내의 클래스 목록을 가져온다.
- 반복문으로 클래스를 하나씩 읽어와서 @Component이 붙어 있는지 확인
- @Component가 붙어 있으면 객체를 생성해서 map에 저장

- Engine의 경우 @Component로 등록하지 않아서 null로 나타났음.