2013-02-09 23 views
0

我想創建一個自定義el函數,以快速方式從dao中選擇選項。我正在使用Spring,我想在我的自定義el函數類中注入spring bean dao。在自定義el函數中注入spring bean

在el函數類中我使用靜態方法,我無法訪問應用程序上下文。 我用了ApplicationContextAware的實現這樣

public class AppContextUtil implements ApplicationContextAware 
{ 

    private ApplicationContext applicationContext; 

    private static final AppContextUtil instance=new AppContextUtil(); 

    private AppContextUtil() 
    { 
    } 

    public static AppContextUtil getInstance() 
    { 
     return instance; 
    } 

    public <T> T getBean(Class<T> clazz) 
    { 
     return applicationContext.getBean(clazz); 
    } 

    /** 
    * {@inheritDoc} 
    */ 
    @Override 
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException 
    { 
     this.applicationContext = applicationContext; 
    } 

} 

但ApplicationContext已空。

訪問的ApplicationContext的唯一途徑是belove

WebApplicationContext appCtx = 
WebApplicationContextUtils.getWebApplicationContext(context.getServletContext()); 
MyDAO myDAO = appCtx.getBean(MyDAO.class); 

但這種方式我需要傳遞的PageContext在El功能PARAMS。

我如何創建一個支持spring bean的el函數類?我如何以靜態方式訪問applicationContext?

謝謝。

+0

我解決了自己:它需要彈簧conf.xml中宣佈AppContextUtil如春豆 – Premier 2013-02-09 09:45:08

回答

0

髒液「注入」的bean或應用程序上下文爲靜態字段:

@Component 
public class AppContextUtil { 

    private static ApplicationContext applicationContext; 

    @Autowire 
    private set ApplicationContext(ApplicationContext applicationContext) { 
     AppContextUtil.applicationContext = applicationContext; 
    } 
}