簡體   English   中英

Spring中自動裝配對象的空指針異常

[英]Null pointer exception for Autowired object in Spring

我正在為SOAP Web服務構建一個新項目。 之前,我使用JDBC層來打開和關閉連接。 現在,我正在使用JDBC模板將其轉換為Spring。 我已經配置了所有層並注釋了組件。 當我嘗試在服務impl類中使用dao bean時,它將拋出空指針異常

@Service
@WebService
public interface Transaction { // Web methods here for SOAP Web service
}

Impl類

@Component
@WebService
public class TransactionImpl implements Transaction{        

    @Autowired
    BBDao dao;  --> This is coming as null when I use it in the method

}

BBDao界面如下

public interface BBDao { /* Methods in it */ }

正在實現BBDao接口的實現類是

public class BBDaoImpl extends JdbcDaoSupport implements BBDao {    

@Autowired
ServletContext ctx; 

@Autowired
DataSource dataSource;

// Methods overriding here 

}

在web.xml中定義的Servlet

<servlet>
    <servlet-name>spring-web</servlet-name>
    <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
            </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>spring-web</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

最后是spring-web-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:component-scan base-package="com.bb.controller,com.bb.dao,com.bb.service" />
<context:property-placeholder location="classpath:datasource-cfg.properties" />


<bean id="bbDAO" class="net.bb.dao.BBDaoImpl">
    <property name="dataSource" ref="dataSource" />
</bean> 

<!-- AS400 Data source Bean -->
<bean id="dataSource"
     class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.ibm.as400.access.AS400JDBCDriver" />
    <property name="url" value="${as400.url}" />
    <property name="username" value="${as400.username}" />
    <property name="password" value="${as400.password}" />
</bean>

<mvc:annotation-driven />

</beans>

BBDao bean對象將作為null出現。

我的配置有任何錯誤嗎? 任何建議將不勝感激。

PS:我也關注了其他帖子,因為大多數帖子只談論組件掃描並且軟件包正確

由於無法為接口創建實例,因此無法在沒有實現的情況下自動裝配接口。 但是您可以嘗試以下方法,看看是否可行。

很少可以做的事情。

添加到您的spring-webservlet.xml

還要參考這個

用戶注釋,例如@ConditionalOnMissingBean(BBDao.class)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM