简体   繁体   English

在自定义el函数中注入spring bean

[英]Inject spring bean in custom el functions

i want to create a custom el functions to get in a fast way select options from dao. 我想创建一个自定义的el函数,以便快速从dao中选择选项。 I'm using Spring and i want to inject spring bean dao in my custom el functions class. 我正在使用Spring,我想在我的自定义el函数类中注入spring bean dao。

In el functions class i'm using static methods and i'm unable to access application context. 在el函数类中,我使用静态方法,并且无法访问应用程序上下文。 I used an implementation of ApplicationContextAware in this way 我以这种方式使用了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;
    }

}

but applicationContext is null. 但是applicationContext为null。

The only way to access to applicationContext is as belove 访问applicationContext的唯一方法就是belove

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

but in this way i need to pass PageContext in el functions params. 但是以这种方式,我需要在el函数参数中传递PageContext。

How i can create an el functions class with spring bean support? 我如何在Spring bean支持下创建el函数类? how i can access in static way to applicationContext? 我如何以静态方式访问applicationContext?

Thank you. 谢谢。

A dirty solution to "inject" a bean or Application Context into an static field: 将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