Unable to instantiate Action, com.pp.action.user.LoginAction, defined for 'login' in namespace '/user'Error creating bean with name 'com.pp.action.user.LoginAction': Injection of resource fields failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'accountDao' must be of type [com.pp.dao.account.AccountDaoImpl], but was actually of type [com.sun.proxy.$Proxy19] com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:318) com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:399) com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:198) org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61) org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39) com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
报错原因:
@Resource private AccountDaoImpl accountDao; @SuppressWarnings("unchecked") @Action(value = "login", results = { @Result(name = "success", type = "json"), @Result(name = "fail", type = "json") }) public String login() throws Exception { System.out.println("test: LoginAction---"); String result = null; Account account = accountDao.getAccountByName(name); if (account == null) { result = "fail"; flag = "pass"; } else if (account.getPwd().equalsIgnoreCase(pwd)) { result = "success"; nickName = account.getName(); flag = "success"; try { session.put("account", account); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } else { result = "fail"; flag = "fail"; } return result; }注入时 accountDao 类型 改为 其接口,
@Resource private AccountDao accountDao;
就ok了
这里面主要涉及到了spring AOP的动态代理:
Spring 有两种代理:动态代理和CGLIB代理(上面的代码中用的是动态代理):
- 动态代理只能对实现了接口的类生成代理,而不能针对类;
- CGLIB代理是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法。