我是Spring的新手,試圖讓事情滾動。我想使用基於xml setter的依賴注入,並避免Java中的'@whatever'標記。Spring 3.1依賴注入失敗
我在Spring 3.1.1中使用了NetBeans 7,並且在項目中也有一些Struts 2代碼,並且工作正常。
我有的問題是,依賴注入似乎並沒有工作(accountService保持NULL),所以我猜我沒有正確配置。任何幫助,將不勝感激!
BaseActionUserAware是需要注射類:
public class BaseActionUserAware extends BaseAction
{
protected AccountService accountService;
protected String username;
@Override
public String execute() {
super.execute();
// accountService = new AccountServiceImpl();
Object accountID = session.get(SessionProperties.ACCOUNT_ID);
if(null != accountID) {
AccountBean account = accountService.getAccount((int)accountID);
username = account.getUsername();
}
return SUCCESS;
}
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
public String getUsername() {
return username;
}
}
...註釋代碼表示想什麼我來完成;我希望accountService被注入AccountServiceImpl。
這裏是我的WEB-INF/applicationContext.xml中:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="accountService" class="hyperbook.service.impl.AccountServiceImpl"/>
<bean id="baseActionUserAware" class="hyperbook.action.BaseActionUserAware">
<property name="accountService" ref="accountService"/>
</bean>
</beans>
...我仔細檢查過的完全限定類名,這些都是正確的。
我最近增加了以下我的WEB-INF/web.xml文件,但它並沒有在所有幫助:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
同樣,任何幫助將真正理解。謝謝!!
[編輯]我還應該提到 - BaseActionUserAware永遠不會在Java中的任何地方特別實例化。相反,它專門用於Struts 2操作類的擴展。因此,applicationContext.xml中的baseActionUserAware定義可能完全錯誤/不需要。我對Spring還不夠了解。
近距離投票甚至更加怪異。 –