是否有一种优雅的方式将spring托管bean注入java自定义/简单标记 [英] is there an elegant way to inject a spring managed bean into a java custom/simple tag

查看:611
本文介绍了是否有一种优雅的方式将spring托管bean注入java自定义/简单标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆使用spring托管bean的java自定义标签..由于我无法找到注入自定义标记的方法,我创建了一个帮助类,为所有弹簧提供静态方法getTheObjectINeedBean()我需要的bean对象..我根本不喜欢这种方法。

I have a bunch of java custom tags that use spring managed beans.. since i cant find a way to inject into a custom tag, i created a helper class that provides static methods to "getTheObjectINeedBean()" for all the spring bean objects i need.. I do not like this approach at all.

我真的希望能够将spring托管bean注入自定义标记

i really want to be able to inject a spring managed bean into the custom tag

有办法吗?就我的研究而言,我知道没有办法做到这一点,因为自定义标签是容器管理的

Is there a way? As far as my research goes, I understand there is no way to do this, because the custom tag is container managed

谢谢,

Billy

推荐答案

你说得对,在jstl标签中没有一种简单的方法可以使用依赖注入,因为它们不是由春天管理,也不可能。但是(至少)有两种解决方法:

You are correct there isn't a simple way to use dependency-injection in jstl tags, because they are not managed by spring, and cannot be. However there are (at least) two workarounds:


  • @Configurable - aspectJ允许您在加载时/编译时插入编织器,这样即使没有弹簧实例化的对象也可以弹出。请参见此处

  • @Configurable - aspectJ allows you to plug a weaver at load-time/compile-time, so that even objects that are not instantiated by spring can be spring aware. See here

您可以为项目创建基本标记类,并调用 init(..) doStartTag(..)方法的c $ c>方法。在那里,你可以从 pageContext 获得 ServletContext ,从而获得spring ApplicationContext (通过 ApplicationContextUtils )。然后:

You can create a base tag class for your project, and call an init(..) method from every doStartTag(..) method. There, you can get the ServletContext from the pageContext, and thus obtain the spring ApplicationContext (via ApplicationContextUtils). Then:

AutowireCapableBeanFactory factory = appCtx.getAutowireCapableBeanFactory();
factory.autowireBean(this);


两种选择都不是完美的,因为它们需要一些附加代码,或一些黑魔法

Neither options are perfect as they require either some additional code, or some "black magic"

这篇关于是否有一种优雅的方式将spring托管bean注入java自定义/简单标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆