我正试图抓住Spring中的自动连接,但我似乎无法正确实例化bean(DocumentBuilder
)。我已经创建了一个自定义JSP标记:
public class MyTag extends SimpleTagSupport {
@Autowired
private DocumentBuilder documentBuilder;
public void setBuilder(DocumentBuilder builder) {
this.documentBuilder = builder;
}
@Override
public void doTag() throws IOException {
// documentBuilder is null in here!
}
}
这是servlet配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scan for HTTP/REST controllers -->
<context:component-scan base-package="the.right.package" />
<context:annotation-config/>
<bean id="documentBuilderFactory"
class="javax.xml.parsers.DocumentBuilderFactory"
factory-method="newInstance">
<property name="validating" value="false" />
<property name="ignoringElementContentWhitespace" value="true" />
</bean>
<bean id="documentBuilder" class="javax.xml.parsers.DocumentBuilder"
factory-bean="documentBuilderFactory"
factory-method="newDocumentBuilder">
</bean>
</beans>
有什么想法吗?
答案 0 :(得分:4)
你只能注入春豆!但是Jsp-Tags不是Spring Beans,因此Autowird注释将被完全忽略,因此该字段为空。
有两种解决方案:
@Configurable
支持。 - 但这需要真正的AspectJ。 (我从来没有尝试过标签,但我想它适用于像其他普通类一样的标签)。 @see Spring Reference: Chapter 7.8.1 Using AspectJ to dependency inject domain objects with Spring RequestContextAwareTag
扩展您的标记。这样可以通过WebApplicationContext
访问getRequestContext().getWebApplicationContext()
。然后,您可以使用WebApplicationContext
获取所需的bean programmatic。答案 1 :(得分:0)
尝试修改这样的代码
public class MyTag extends SimpleTagSupport {
private DocumentBuilder documentBuilder;
@Autowired
public void setBuilder(DocumentBuilder builder) {
this.documentBuilder = builder;
}
@Override
public void doTag() throws IOException {
// documentBuilder is null in here!
}
}
答案 2 :(得分:0)
如果将标记类标记为Spring bean,则可以使用@Autowired。但它很愚蠢,因为简单的标签不是通过容器缓存的。每个请求都会创建自己的标记实例,但只有上下文才会启动。