回复 楼主 JeffLi
今天换了个思路
写一单例来加载一次配置文件
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppContext {
private static ApplicationContext appContext = null;
private AppContext() {
}
public static synchronized ApplicationContext getAppContext() {
if (appContext == null) {
appContext =
new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" });
}
return appContext;
}
}
然后applicationContext.xml中配置
<bean id="AppContext" class="com.jeff.persist.AppContext"/>
<bean id="LoginAction" class="com.jeff.struts.action.LoginAction">
<property name="appContext">
<ref bean="AppContext"/>
</property>
</bean>
Action改成:
public class LoginAction extends Action {
private ApplicationContext appContext;
public void setAppContext(ApplicationContext appContext) {
this.appContext = appContext;
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LoginForm loginForm = (LoginForm) form;
ActionForward forward = mapping.getInputForward();
String userName = loginForm.getUsername();
String password = loginForm.getPassword();
UserService userService = (UserService)
appContext
.getBean("UserService");
User user = userService.getUserByUserName(userName);
System.out.println(userName + password);
if (user != null) {
if (password.equals(user.getPassword())) {
forward = mapping.findForward("success");
} else {
forward = mapping.findForward("fail");
}
}
return forward;
}
}
没提示出错.但是启动Tomcat时报错:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'LoginAction' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [com.jeff.persist.AppContext] to required type [org.springframework.context.ApplicationContext] for property 'appContext'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [com.jeff.persist.AppContext] to required type [org.springframework.context.ApplicationContext] for property 'appContext': no matching editors or conversion strategy found
这种出错.spring不能往Servlet文件中注入.还是不能注入spring的ApplicationContext.xml的加载类...
哎..还是困在怎么加载ApplicationContext.xml文件.和使用getBean()方法使用上...求高手指点迷津啊..