2016-10-14 2 views
0

내 클래스의 주 콩은 매우 비싸고 따라서 한 번만 생성 된 다음 필요한 여러 Utils로 전달되어야하는 객체가 있습니다.콩에 대한 스프링 액세스

public class DaemonBean implements InitializingBean 
{ 
    ReallyExpensiveToCreate obj; 

    public ReallyExpensiveToCreate getReallyExpensive() { return obj; } 

    @Override 
    public void afterPropertiesSet() 
    { 
     //initialize and build ReallyExpensiveToCreate 
    } 
} 

이 개체는 정적 함수 집합으로 구성된 Util 클래스에서 필요합니다.

public class Util 
{ 
    public static ReallyExpensiveToCreate objRef = getReallyExpensiveObj(); 

    private ReallyExpensiveToCreate getReallyExpensiveObj() 
    { 
    //Get Daemon obj from Spring and call daemonObj.getReallyExpensive(); 
    } 

    public void func1() { //Use objRef in logic } 
} 

스프링에서 데몬 obj를 어떻게 얻을 수 있습니까? 데몬 obj에 대한 참조를 얻을 수 있도록 호출 할 코드가 확실하지 않습니다. ApplicationContext가 사용 된 곳에서 코드 스 니펫을 보았지만 어떻게 사용되는지는 확신 할 수 없습니다.

답변

1

당신은 봄에, 서비스 로케이터 패턴에 대한

구현을 찾고

당신은 ApplicationContextAware을 등록하고 ApplicationContext에 대한 참조를 얻고 정적 콩 역할을 할 수

public class ApplicationContextUtils implements ApplicationContextAware { 
private static ApplicationContext ctx; 

private static final String USER_SERVICE = "userServiceBean"; 

    @Override 
    public void setApplicationContext(ApplicationContext appContext) 
     throws BeansException { 
    ctx = appContext; 

    } 

    public static ApplicationContext getApplicationContext() { 
    return ctx; 
    } 

    public static UserService getUserService(){return ctx.getBean(USER_SERVICE);} 

} 
0
public class Util { 

    private static ReallyExpensiveToCreate objRef; 

    public void objectFunction() { 
     objRef.doSomething(); 
    } 

    public static void staticFunction() { 
     objRef.doSomething(); 
    } 

    @Autowired 
    public void setReallyExpensiveBeanToCreate(DaemonBean daemonBean) { 
     Util.objRef = daemonBean.getReallyExpensive(); 
    } 
} 
관련 문제