gpt4 book ai didi

java - 发生 UnsatisfiedDependencyException 错误

转载 作者:行者123 更新时间:2023-12-02 02:08:30 26 4
gpt4 key购买 nike

我有以下代码和@ComponentScan(basePackages = "com.project.shopping"),包结构为

com.project.shopping.Controller
com.project.shopping.configuration
com.project.shopping.entity
com.project.shopping.services
com.project.shopping.dao

我运行应用程序时的错误是

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl': Unsatisfied dependency expressed through field 'userDaoImpl'; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userDaoImpl' is expected to be of type 'com.project.shopping.dao.impl.UserDaoImpl' but was actually of type 'com.sun.proxy.$Proxy56'
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587)

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'userDaoImpl' is expected to be of type 'com.project.shopping.dao.impl.UserDaoImpl' but was actually of type 'com.sun.proxy.$Proxy56'
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1148)
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)

UserDaoImpl.java

@Transactional
@Repository
public class UserDaoImpl implements UserDao{
@Autowired
private SessionFactory sessionFatory;

public List<User> getAllUser() {
return this.sessionFatory.getCurrentSession().createQuery("from user").list();

}
}

可以使用@Repository注释接口(interface)及其实现,也可以在服务接口(interface)及其实现中使用@Service注释UserDao.java

@Repository
public interface UserDao {
public List<User> getAllUser();
}

UserService.java

@Service
public interface UserService {
public List<User> listUser();
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDaoImpl userDaoImpl;
public List<User> listUser() {

return userDaoImpl.getAllUser();
}
}

UserController.java

@Controller
@RequestMapping("/")
public class UserController {
@Autowired
UserServiceImpl userServiceImpl;
@RequestMapping(method = RequestMethod.GET,value = "/allusers" , produces = "application/json")
@ResponseBody
public List<User> sayHello(ModelMap model) {

return userServiceImpl.listUser();
}

最佳答案

我们大多需要在实现类上使用@Repository、@Service、@Component等,Spring为标有这些注解的类创建Bean。

此外,在您的 *ServiceImpl 和 *DaoImpl 中,@Autowire 的使用将主要在实现类的接口(interface)上。​​

建议

  • 从 UserDao 中删除 @Repository,从 UserService 中删除 @Service。
  • 分别在 UserServiceImpl 和 UserController 中 Autowiring UserDao 和 UserService,而不是 UserDaoImpl 和 UserServiceImpl。

关于java - 发生 UnsatisfiedDependencyException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50383053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com