2009-08-18 72 views
13

目前我需要Spring bean的JSP 2.0标签使用此代码:如何将spring bean注入到jsp 2.0 SimpleTag中?

ac = WebApplicationContextUtils.getWebApplicationContext(servletContext); 
ac.getBeansOfType(MyRequestedClass.class); 

的我只是得到第一个匹配的bean。

此代码工作正常,但不想要的缺点,我花了大约一半我的网页渲染时间查找春豆,因为这发生的每一个标签调用时。我在想也许把bean放到应用程序范围或至少会话范围内。但是,处理这个问题最聪明的方法是什么?

+0

“[http://stackoverflow.com/questions/3445908/is-there-一个优雅的方式注入一个弹簧管理的bean到一个java自定义简单] [1]'有一个很好的答案。 [1]:http://stackoverflow.com/questions/3445908/is-there-an-elegant-way-to-inject-a-spring-managed-bean-into-a-java- custom-simpl – Angus 2012-03-02 20:01:48

回答

11

我首先想到的是,你一定要春呼叫贵吗?这些东西是非常优化的,所以在试图优化它之前确保它确实是一个问题。

假设它是问题,那么可替换的是在InternalResourceViewResolverexposeContextBeansAsAttributesexposedContextBeanNames性质。您可以使用其中一个(但不能同时使用)将部分或全部bean公开为JSP属性。

这就提出了一个可能的实际Spring Beans注入到你的标签类。例如,在你的Spring上下文,你可以有:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="exposeContextBeansAsAttributes" value="true"/> 
</bean> 

<bean id="myBean" class="com.x.MyClass"/> 

你的JSP:

<MyTag thing="${myBean}"/> 

所以如果MyTag定义MyClass类型的属性thing,在myBean的Spring bean应该得到注入作为一个正常的JSP属性。

+0

是的,它们相对较贵。特别是因为标签被用于循环。我们使用60-70%的执行时间来讨论上述逻辑的1-200次调用。其余的代码是干净优雅的。 – krosenvold 2009-08-19 04:25:12

8

一个更简单的方法是在你的标签类中使用@Configurable注解,这将使Spring自动连线当标签被初始化的依赖关系。任何必需的依赖关系都可以使用@AutoWired标注进行标记,并且即使标签未在Spring容器中初始化,Spring也会在依赖项中进行连接。

+0

您可以扩展吗?谢谢 – 2015-08-19 08:58:03

5

另一种方式实现这一目标是使用一个静态属性来保存的依赖。就像下面:

public class InjectedTag extends SimpleTagSupport { 
//In order to hold the injected service, we have to declare it as static 
    private static AService _service; 
/***/ 
@Override 
public void doTag() throws IOException {  
      getJspContext().getOut(). 
      write("Service injected: " + _service + "<br />");  
} 
public void setService(AService service) { 
     _service = service;  
} 
} 

在你的ApplicationContext,你必须注册都让JSP标签可以得到由Spring启动一个机会。我们才好用魔法......

<bean id="aService" class="com.foo.AService"> 
    <!-- configure the service. --> 
</bean> 
<bean class="com.foo.InjectedTag" > 
    <property name="service"><ref local="aService"/></property> 
</bean> 

很酷吧,现在aService可见在我们的JSP标签:)