【问题标题】:Parameter 0 of constructor in ServiceImpl required a bean of type DAO that could not be foundServiceImpl 中构造函数的参数 0 需要一个找不到的 DAO 类型的 bean
【发布时间】:2019-09-08 05:36:01
【问题描述】:

在创建将使用 Hibernate 作为 ORM 将对象保存在数据库中的服务时,我无法启动应用程序。

我正在使用 Spring Boot 和 Hibernate。我的服务实现:

@Service
public class PropertyServiceImpl implements PropertyService{

private PropertyDAO propertyDAO;

    public PropertyServiceImpl(){
    System.out.println("inside propertyserviceimpl constructor");
}

@Autowired
public PropertyServiceImpl(PropertyDAO propertyDAO){
    this.propertyDAO = propertyDAO;
    System.out.println("inside save");
}

@Transactional
public void save(Property property) {
    propertyDAO.save(property);
}

@Override
public List findAll() {
    // TODO Auto-generated method stub
    return null;
}

}

PropertyDAO.java

public interface PropertyDAO {

public void save(Property property);

 }

PropertyDAOImpl 实现 DAO

public class PropertyDAOImpl implements PropertyDAO{

@Autowired
private SessionFactory sessionFactory;

public void save(Property property) {
    Session currentSession = sessionFactory.getCurrentSession();
    currentSession.saveOrUpdate(property);
}

}

我在启动 SpringBoot 应用程序时收到以下错误消息。

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.flarow.flarowhomes.services.PropertyServiceImpl required a bean of type 'com.flarow.flarowhomes.dao.PropertyDAO' that could not be found.


Action:

Consider defining a bean of type 'com.flarow.flarowhomes.dao.PropertyDAO' in your configuration.

【问题讨论】:

  • 显示未找到的PropertyDAO
  • 用 PropertyDAO 更新了问题
  • 但是标记为 Spring bean 并实现该 PropertyDAO 接口的具体类在哪里?
  • PropertyDAOImpl 实现 PropertyDAO
  • 但它是 Spring bean 吗?它是否具有将其标记为 Spring bean 的 Component 注释(或 Service 注释或 Repository 注释)? Spring 只注入 Sring bean。不是随机课程。

标签: java spring hibernate spring-boot


【解决方案1】:

@Repository 添加到您的DAO 实现类中,以便找到它:

@Repository
public class PropertyDAOImpl implements PropertyDAO {

实现传统 Java EE 模式(例如“数据访问对象”)的团队也可以将此原型应用于 DAO 类,但在这样做之前应注意了解数据访问对象和 DDD 样式存储库之间的区别。

【讨论】:

  • 这有助于我摆脱我所面临的错误。但是引入了一个新的错误Description: Field sessionFactory in com.flarow.flarowhomes.dao.PropertyDAOImpl required a bean of type 'org.hibernate.SessionFactory' that could not be found. Action: Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.
【解决方案2】:

如下更改您的 PropertyDAO:

public interface PropertyDAO extends JpaRepository<Property, Integer>{ }

【讨论】:

  • 这需要我将保存方法的返回类型从 void 更改。
  • 是的,你会归还你保存的财产。
猜你喜欢
  • 2019-10-20
  • 2019-03-21
  • 2021-02-02
  • 2020-02-23
  • 2020-08-26
  • 2023-02-05
  • 1970-01-01
  • 2021-12-10
  • 2022-11-29
相关资源
最近更新 更多