gpt4 book ai didi

Spring和 Autowiring : NullPointerException

转载 作者:行者123 更新时间:2023-12-02 09:37:36 25 4
gpt4 key购买 nike

我试图掌握 Spring 中的 Autowiring ,但我似乎无法正确实例化 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>

有什么想法吗?

最佳答案

只能注入(inject) Spring Bean !但Jsp-Tags不是Spring Bean,因此Autowird注释将被完全忽略,因此该字段为空。

有两种解决方案:

关于Spring和 Autowiring : NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8243847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com