java – spring 3 @controller无法注入具有@Transactional的服务对象

我正在使用Spring 3 MVC,我在注入Objects时遇到了问题.
我用@Controller创建了Controller对象.我用@Service对象创建了一个服务对象.我用AutoWire在服务器中注入了服务对象.
我创建了DAO对象,并注入了服务对象,并测试了应用程序,它运行正常.
然后我把@Transactional放在DAO上,然后它也运行良好.但是当我把@Transactional放在服务对象上时,它给了我这个问题.在部署时,在控制器上它称为“

Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘loginController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.erudicus.controller.LoginController.setLoginService(com.erudicus.model.service.LoginServiceImpl); nested exception is java.lang.IllegalArgumentException: argument type mismatch”.

这是守则
调节器

@Controller
public class LoginController {
     private static Logger LOG = Logger.getLogger(LoginController.class);

    private LoginServiceImpl loginService = null;


    public LoginServiceImpl getLoginService() {
        return loginService;
    }

    @Autowired
    public void setLoginService(LoginServiceImpl loginService) {
                this.loginService = loginService;
    }

    @RequestMapping(value="/login" , method= RequestMethod.GET)
    public String login(Model model) {
        model.addAttribute(new Login());
            return "login";
    }

    @RequestMapping(value="/loginDetails", method=RequestMethod.POST)
    public ModelAndView create(@Valid Login login, BindingResult result) {
      }
}

服务对象

@Service
public class LoginServiceImpl implements LoginService {

    private LoginDao loginDao = null;


    public LoginDao getLoginDao() {
        return loginDao;
    }

    @Autowired
    public void setLoginDao(LoginDao loginDao) {
        this.loginDao = loginDao;
    }

    @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    public Login getUserDetails(String userId) {
           return getLoginDao().getUserDetails(userId);
    }
}

@Service
@Transactional(propagation = Propagation.MANDATORY)
public class LoginDaoImpl extends SqlSessionDaoSupport implements LoginDao {

    @Transactional(readOnly = true, propagation = Propagation.MANDATORY)
    public Login getUserDetails(String userId) {
    }
}

在我指定的配置中

<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
    <!-- enable autowire -->
    <!-- enable transaction demarcation with annotations -->
    <tx:annotation-driven transaction-manager="txManager"/>
 <context:annotation-config/>

任何人都可以请求帮助

最佳答案
将字段定义为接口,而不是具体类. (所以UserService而不是UserServiceImpl).您可以在具体类上添加@Transactional注释 – 它将起作用.

问题是默认情况下spring使用JDK代理(java.lang.reflect.Proxy),它们是仅限接口的代理.然后,调用处理程序会使用您的具体类,但您无法转换它.

如果没有接口,spring会使用另一个方法 – CGLIB,它为目标类创建子类以生成代理.

您可以使用< aop:scoped-proxy />为每个bean配置代理stragegy(proxy-target-class).

转载注明原文:java – spring 3 @controller无法注入具有@Transactional的服务对象 - 代码日志