【问题标题】:Inject spring bean in custom el functions在自定义el函数中注入spring bean
【发布时间】:2013-01-25 00:34:54
【问题描述】:

我想创建一个自定义 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 为空。

访问applicationContext的唯一方法是belove

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

但是这样我需要在 el 函数参数中传递 PageContext。

如何创建一个支持 spring bean 的 el 函数类?如何以静态方式访问 applicationContext?

谢谢。

【问题讨论】:

  • 我自己解决了:需要在spring-conf.xml中声明AppContextUtil为spring bean

标签: java spring spring-el


【解决方案1】:

将 bean 或应用程序上下文“注入”到静态字段的肮脏解决方案:

@Component
public class AppContextUtil  {

    private static ApplicationContext applicationContext;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多