2012-03-29 58 views
7

我在Spring bean中注释为@Resource的字段遇到问题。我拥有的一切:Spring @Resource Handling

场,与setter方法,注释@Resource

@Resource 
private URL someUrl; 

public void setSomeUrl(URL someUrl) { 
    this.someUrl = someUrl; 
} 

<env-entry>标签在我的部署描述符(web.xml)

<env-entry> 
    <env-entry-name>someUrl</env-entry-name> 
    <env-entry-type>java.net.URL</env-entry-type> 
    <env-entry-value>http://somedomain.net/some/path</env-entry-value> 
</env-entry> 

应用程序无法启动了BeanCreationException,我不期待,因为我不一定希望春天注入Spring管理的bean。我希望Spring能够处理@Resource并检索JNDI资源。

这是Spring 2.5.6SEC03和bean本身被注释为@Service用于自动装配到其他@Component实例中。在这种情况下,Servlet容器是Tomcat 7,但最终会部署到Weblogic 10上,所以虽然我希望理想的解决方案可以同时使用,但Weblogic是必备的。

我在Spring 2.5中滥用了这个特性吗?一般来说?有一些我失踪了吗?我误解了JNDI?所有的帮助表示赞赏。谢谢。

回答

7

如果您使用的是Spring Stereotype注释(@Service,@Component ...),那么您可能会在弹簧配置中包含<context:component-scan />元素来提取它们。这样做很好,但它会自动注册CommonAnnotationBeanPostProcessor与应用程序上下文as stated just above the second note in this link

包含CommonAnnotationBeanPostProcessor的问题在于Spring处理了@Resource注解,并将尝试从其应用程序上下文中注入bean。您可以注册您自己的CommonAnnotationBeanPostProcessor bean,并告诉Spring允许通过将alwaysUseJndiLookup属性设置为true来配置bean,从而允许直接JNDI访问这些@Resource

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"> 
    <property name="alwaysUseJndiLookup" value="true"/> 
</bean> 

注重链接的文档中的注意事项:

注:默认CommonAnnotationBeanPostProcessor会将由注册“背景:注解配置”和“上下文:组件扫描” XML标签。如果您打算指定自定义的CommonAnnotationBeanPostProcessor bean定义,请在那里删除或关闭默认的注释配置!

+0

太棒了,这完全工作!我还发现,您可以强制CommonAnnotationBeanPostProcessor通过为注解体中的“mappedName”生成一个值来执行JNDI查找。说了这么多,并且在完成这项工作之后,我了解到我们的标准企业部署过程将不支持多个部署描述符。我应该在所有部署中使用同一个。所以,这种方法是行不通的。 – 2012-03-30 19:37:41