인프런 커뮤니티 질문&답변
FactoryBean 관련 질문
작성
·
136
0
안녕하세요 factory bean 에 대해서 학습하다 보니 질문이 생겼습니다.
일단 구성은
interface(ABC)를 상속 받은 객체 (A, B, C) 요렇게 있을 때 factory pattern으로 동적으로 A, B, C객체를 가져오도록 구현하고 있습니다. 그리고 A, B, C 모두 Bean으로 등록 되었기 때문에 di 도 가능해야 하는 상황 입니다. 이때 A,B,C객체를 모두 Bean으로 등록하고 런타임에서 3객의 객체를 가져오려면 어떤 방법으로 구현 해야하나요?
만약 FactoryBean을 사용하지 않고 다른 방법을 사용할 수 있으면 예시를 보여주실 수 있으신가요?
public interface ABC {
void hello();
}
public class A implements ABC {
@Autowired
private Hello hello;
void hello() {
// codes..
}
}
public class B implements ABC {
@Autowired
private Hello hello;
void hello() {
// codes..
}
}
public class C implements ABC {
@Autowired
private Hello hello;
void hello() {
// codes..
}
}
public class ABCFactory implements FactoryBean<ABC> {
private Type type;
@Override
public ABC getObject() throws Exception {
if (type == Type.A) {
return new A();
} else if (type == Type.B) {
return new B();
}
return new C();
}
@Override
public Class<?> getObjectType() {
return ABC.class;
}
@Override
public boolean isSingleton() {
return true;
}
public void setType(Type type) {
this.type = type;
}
}
// 사용 시점
@Service
public class Use {
// factory class
public void use (Type type) {
// type 이 A 일 경우 A객체 반환
// type 이 B 일 경우 B객체 반환
// type 이 C 일 경우 C객체 반환
return // obj
}
}
답변
답변을 기다리고 있는 질문이에요
첫번째 답변을 남겨보세요!




