用Java将服务注入DAO的好方法

时间:2018-08-03 21:36:07

标签: java dependency-injection data-access-layer

我有一个场景,我需要在DAO层中调用一些服务,以基于来自数据库(结果集中)的输入来获取一些数据。那么最好的方式实例化服务。插入DAO构造函数或实例化结果集。请参阅以下示例以进行清晰的了解

 public class ParticipationDao {

  private ConnectionFactory connectionFactory'
  private int userId;

    /**
     * Constructor which injects dependencies
     */
    public  ParticipationDao(String userId, ConnectionFactory connectionFactory) {
        this.userId = userId;
        this.connectionFactory = connectionFactory;

    }

    public List<Participation> getParticipantDetails(Integer studyId) throws StudyParticipationException {

        List<Participation> participationList = new ArrayList<>();
        String query = //some QUERY.....
        try (Connection connection = connectionFactory.getConnection();
                PreparedStatement stmt = connection.prepareStatement(query); ) {
            stmt.setInt(1, studyId);
            try (ResultSet rs = stmt.executeQuery();) { 
                while (rs.next() ) {
                    Participation p = new Participation();
                    //SOME OTHER ASSIGNMENTS ......
                    String modifiedUserId = rs.getString("ModifiedByID");
                    // TODO call some service here to get the username and assign to the setUserName method.
                    p.setUserName(assignHere);

                    participationList.add(p);
                } 
            }
        } catch (SQLException | ConnectionFactoryException e) {
            throw new StudyParticipationException(e.getMessage(), e);
        }
        return participationList;
    }

    }

是将UserService注入到DAO中的好方法,如下所示,因为这与DAO逻辑无关,因此是这样编写的好方法。

public  ParticipationDao(String userId, ConnectionFactory connectionFactory, UserService userService) {
        this.userId = userId;
        this.connectionFactory = connectionFactory;
        this.userService = userService;

    }

建议使用任何好的方法。谢谢你

2 个答案:

答案 0 :(得分:0)

是的,这很好,因为您的依赖项是从外部(即,将使用dao的任何人)注入的。这样,您的dao不需要了解服务本身的构造细节,并且服务可以自由更改,但是只要提供了依赖关系,从dao的角度来看就没有问题了。 。

想象一下,您的dao构建了自己的用户服务实例。如果由于需要更多细节而修改了用户服务构造函数,将会发生什么?然后,您还应该修改dao。这个不好。发明了依赖注入技术来解决这些问题。

上一点对于测试也很有用,因为它可以轻松模拟依赖项。

答案 1 :(得分:0)

好坏实际上是一个相对的限定词,在软件世界中,如果大多数工程师遵循相同的一组实践或模式通常是一件好事,以便代码阅读器易于遵循和以后对代码进行操作。 在您的情况下,人们通常会尽量减少DAO,如果您需要使用来自其他服务的信息来丰富DAO提取的对象,那么最好在服务中做到这一点,例如ParticipationService

public ParticipationService(UserService userService, ParticipationDao Participation dao) {
    this.userService = userService;
    this.dao = dao;
}

public List<Participation> getParticipantDetails(Integer studyId) {
     return this.dao.getParticipantDetails(studyId).forEach(p -> {
         p.setUserName = userService.lookup(...);
     });
}
相关问题