Java – how do I handle injecting dependencies into the rich domain model?

How do you handle injecting dependencies into model objects in a web server project with a rich domain model (application logic in the model, not in services)? What's your experience?

Do you use some form of AOP? Like the springs @ configurable annotation? Load time or build time? What's your problem?

Do you use manual injection? How do you handle different instantiation scenarios (create objects through libraries [such as hibernate], create objects with "new...)?

Or do you inject dependencies in other ways?

Solution

We use spring's @ configurable (and the regular new operator), which is like charm No more anemic domain models Finally, this is a more object-oriented design, isn't it:

Person person = new Person(firstname,lastname);
// weird
peopleService.save(person);
// good (save is @Transactional)
person.save();

Mail mail = new Mail(to,subject,body);
// weird
mailService.send(mail);
// good (send is @Transactional)
mail.send();

We haven't done any performance comparison yet So far, we have not felt the need to do so at all

Editor: This is what humans look like:

@Configurable("person")
public class Person {
    private IPersonDAO _personDAO;
    private String _firstname;
    private String _lastname;

    // SNIP: some constructors,getters and setters

    @Transactional(rollbackFor = DataAccessException.class)
    public void save() {
        _personDAO.save(this);
    }

    @Transactional(readOnly = true)
    public List<Role> searchRoles(Company company) void{
        return _personDAO.searchRoles(this,company);
    }

    // it's getting more interesting for more complex methods
    @Transactional(rollbackFor = DataAccessException.class)
    public void resignAllRoles(Company company) {
        for (Role role : searchRoles(company)) {
            role.resign();
        }
    }
}

// the implementation Now looks like this
personService.getPerson(id).resignAllRoles(company);

// instead of this
roleService.resignAll(personService.searchRoles(personService.getPerson(id),company));

This is the spring configuration:

<context:spring-configured />
<bean id="person" class="org.example.model.Person" lazy-init="true">
  <property name="personDAO" ref="personDAO" />
</bean>

Note: as you can see, there are still services around, such as searching for objects (personservice. Getperson (ID)), but all methods that operate on the passed objects (such as people) will be moved to the class itself (i.e. person. Save () instead of personservice save(person)). The method itself remains unchanged and is applicable to any underlying data access layer (pure JDBC, hibernate, JPA,...) It just moves to where it belongs

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>