簡體   English   中英

在自定義el函數中注入spring bean

[英]Inject spring bean in custom el functions

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

在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為null。

訪問applicationContext的唯一方法就是belove

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

但是以這種方式,我需要在el函數參數中傳遞PageContext。

我如何在Spring bean支持下創建el函數類? 我如何以靜態方式訪問applicationContext?

謝謝。

將bean或應用程序上下文“注入”到靜態字段中的骯臟解決方案:

@Component
public class AppContextUtil  {

    private static ApplicationContext applicationContext;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM