There is an elegant way to insert spring managed bean in custom / simple java tag

I have a bunch of java user tags that use spring managed beans .. since I cannot find a way to insert into the user tag, I created a helper class that provides static methods for getProObjectINeedBean () for all spring bean objects that I are needed. I don't like this approach at all.

I really want to be able to embed a spring driven bean in a custom tag

Is there any way? As for my research, I understand that there is no way to do this, because the user tag is controlled by the container

Thank,

Billy

+11
java spring inversion-of-control jstl
Aug 10 2018-10-10T00:
source share
3 answers

You are right that there is no easy 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 allows you to attach a weaver at load / compile time, so even objects that are not created using spring can be spring aware. See here

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

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

None of the options are perfect, because this requires either some additional code or some "black magic"

+7
Aug 10 '10 at 5:59
source share

To go to the @Bozho post, I got this to work as follows: (in spring 3.0 there is no ApplicationContextUtils that I could find)

 public class LocationTag extends RequestContextAwareTag { @Autowired PathComponent path; ... @Override protected int doStartTagInternal() throws Exception { if (path == null) { log.debug("Autowiring the bean"); WebApplicationContext wac = getRequestContext().getWebApplicationContext(); AutowireCapableBeanFactory acbf = wac.getAutowireCapableBeanFactory(); acbf.autowireBean(this); } return SKIP_BODY; } } 
+7
Mar 02 2018-12-12T00:
source share

The solution described above works, but some background and additional pieces of code are likely to be useful.

1) The doStartTagInternal method is called by the doStartTag method. 2) I was forced to set pageContext first before using doStartTag 3) I looked at the bean, as opposed to auto-tuning. This seems simpler to me: (YourBeanProxy) autowireCapableBeanFactory.getBean ("yourBeanName")

Hope this additional info is helpful.

0
Jun 18 '15 at 12:50
source share



All Articles