我是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还不够了解。
近距离投票甚至更加怪异。 –