使用 XFire 發布 WebService,Service 實現類中 @Autowired 注入的 Mapper 始終為 null,導致空指針異常。常規 Spring 掃描、@Component 等手段均無效。
XFire 預設使用 XFireConfigurableServlet 且通過 services.xml 配置服務,此模式下服務實例由 XFire 容器管理,不在 Spring 容器生命週期內,故無法享受 Spring 依賴注入。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,/WEB-INF/xfire-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>XFireServlet</servlet-name>
<!-- 關鍵:使用 Spring 整合 Servlet -->
<servlet-class>org.codehaus.xfire.spring.XFireSpringServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XFireServlet</servlet-name>
<url-pattern>/servlet/XFireServlet/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>XFireServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<!-- 引入 XFire 核心配置 -->
<import resource="classpath:org/codehaus/xfire/spring/xfire.xml"/>
<!-- URL 映射到服務 Bean -->
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/SSOMethodsServices"><ref bean="sso"/></entry>
</map>
</property>
</bean>
<!-- 核心:XFireExporter 導出 Spring Bean 為 WebService -->
<bean id="sso" class="org.codehaus.xfire.spring.remoting.XFireExporter">
<property name="serviceFactory"><ref bean="xfire.serviceFactory"/></property>
<property name="xfire"><ref bean="xfire"/></property>
<property name="serviceBean"><ref bean="SSOMethodsImpl"/></property> <!-- 引用 Spring Bean -->
<property name="serviceClass"><value>com.test.sso.SSOMethodsServices</value></property>
</bean>
</beans>
<bean id="SSOMethodsImpl" class="com.test.sso.impl.SSOMethodsImpl" /> <!-- 其他 Mapper、DataSource 等正常配置 -->
@Service("SSOMethodsImpl") // 或在 XML 定義
public class SSOMethodsImpl implements SSOMethodsServices {
@Autowired
private AccountMapper accountMapper; // 現在可正常注入
public void someMethod() {
accountMapper.doSomething(); // 不再為 null
}
}
| 配置項 | 錯誤方式(原生 XFire) | 正確方式(Spring 整合) |
|---|---|---|
| Servlet 類 | XFireConfigurableServlet | XFireSpringServlet |
| 服務配置 | META-INF/xfire/services.xml | xfire-servlet.xml (Spring Bean) |
| 實例管理 | XFire 容器 | Spring 容器 |
| 依賴注入 | 不支援 | 完整支援 |
https://ip:port/project/services 確認服務發布SSOMethodsImpl Bean核心原則:讓 Spring 管理服務實例生命週期,XFire 僅負責協議層導出。同理適用於 CXF、Axis2 等 WebService 框架整合 Spring。