Spring MVC和自定义标签

kxeu7u2r  于 6个月前  发布在  Spring
关注(0)|答案(3)|浏览(81)

我想在spring-mvc应用程序中的自定义taglibs中使用spring-beans。由于TagLib-beans不是由spring示例化的,所以我不能使用dependnecy-injection。
我的下一个想法是通过拦截器将spring-context添加到请求中,并从tag-class中的request获取它。
有没有更好的方法在taglibs中使用spring?spring中有没有什么现成的东西?如果spring-mvc中还没有customtag-support,有没有一种方法可以用依赖项填充一个receiving对象?

public class MyTag extends TagSupport {
  @Autowired 
  private MyObject object;

  public void setMyObject(MyObject myObject) {
    this.myObject = myObject;
  }

  public int doEndTag() {
    ApplicationContext context = request.getAttribute("context");
    context.populate(this);

    return object.doStuff();
  }
}

字符串

pkmbmrz7

pkmbmrz71#

最后,实现这一点的有效方法是将应该由spring初始化的字段声明为static,并让其初始化一个Tag示例

public class MyTag extends TagSupport {
  private static MyObject myObject;

  @Autowired
  public void setMyObject(MyObject myObject) {
    MyTag.myObject = myObject;
  }

  public int doEndTag() {
    return object.doStuff();
  }
}

字符串

wecizke3

wecizke32#

你应该更喜欢把这个逻辑放到你的控制器中,如果你真的需要这样做,你可以写一个实用类来从应用程序上下文中检索bean。

public class AppContextUtil implements ApplicationContextAware 
{
    private static final AppContextUtil instance = new AppContextUtil();
    private ApplicationContext applicationContext;

    private AppContextUtil() {}

    public static AppContextUtil getInstance() 
    {
        return instance;
    }

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

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

字符串
然后,您可以像这样检索bean:

AppContextUtil.getInstance().getBean(MyObject.class);

whhtz7ly

whhtz7ly3#

在控制器中,将对象放入模型中。
该对象现在可以在作为标记一部分的HttpRequest对象中找到。
控制器:

model.addAttribute("item", item);

字符串
Jsp文件:

<%= ((com.content.CmsItem)(request.getAttribute("item"))).getId() %>


如果你必须自动布线,请查看我在' is there an elegant way to inject a spring managed bean into a java custom/simple tag '上的解决方案

相关问题