Selma BA
Selma BA

Reputation: 149

@Inject of multiple DAO

I would inject two DAO in the same service class and I did it as follows:

@Transactional
public class TestData {

    private final UserDao userDao;
    private final ExerciseDao exerciseDao;

    @Inject
    public TestData(final UserDao userDao,final ExerciseDao exerciseDao) {
        this.userDao = userDao;
        this.exerciseDao = exerciseDao;
    }
}

Is it the right way ?

In fact, i tried to create a TestData Class to initialize some records fo HSQL dataBase.

So, i injected the two DAO then i used them to create User and it's Exercice.

and when i tried to call getExercices or getUsers REST services trougth HTTP URL an error with 500 status appeared:

<h2>HTTP ERROR 500</h2> <p>Problem accessing Reason: <pre> Request failed.</pre></p><hr /><i><small>Powered by Jetty://</small></i><br/>

Upvotes: 0

Views: 309

Answers (1)

Andrew
Andrew

Reputation: 49606

Do you want to hear whether there is possible to inject 2 fields by 1 annotation?

Yes, it is possible. You have already done this.

Is that a good practice?

Personally, I prefer field/setter injections. In this case, I am not dependent on constructors and can prevent unnecessary code. Constructor injection makes your code container-agnostic. Whether you use CDI container (e.g. Spring) or not, you have to initialize an instance using this particular constructor.

Upvotes: 1

Related Questions