我有以下代码和@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以及服务接口注释接口及其实现是否正常,并使用@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();
}
答案 0 :(得分:2)
我们主要需要在实现类上使用@ Repository,@ Service,@ Component等,为使用这些注释标记的类创建Spring Create Beans。
同样在你的* ServiceImpl&amp; * DaoImpl,用法@Autowire将主要在实现类的接口上。
建议