Tao
Tao

Reputation: 990

in Spring, what is the best way to dynamically create different objects of a certain class, each object being able to access a Spring bean?

Say I have a file with each line depicting a different command (but of the same kind), which I want to read out and check and run and maybe do other operations such as merging, comparing and most importantly, store the commands into database.

To do that, I create the Command Class, and new a new Command object while reading each line of the file. Now the problem is, a Command object need to make use of, say a Spring bean which provides database access. As a result, I have to pass in that bean as a constructor argument of the Command class, which is very ugly, which doesn't seem to be the "Spring way"... and I don't want to use ApplicationContextAware to make my class coupled to the Spring context.

Is there a best practice for this situation?

I very new to Spring and I know it might be a dumb question ...

Upvotes: 1

Views: 192

Answers (2)

Sebastian Piu
Sebastian Piu

Reputation: 8008

I would create a CommandFactory that is coupled with spring and use that in your consumer instead. If the factory implements an interface you are not coupling yourself in the consumer and you don't close your possibilities of using a different -non spring coupled- one at a later point (e.g. testing).

Upvotes: 1

Ralph
Ralph

Reputation: 120811

In this case I think it is the best way to make the classes created by new Spring Beans.

Therefor annotate them with @Configurable, enable AspectJ, and read the Spring Reference Chapter 7.8.1 Using AspectJ to dependency inject domain objects with Spring

Upvotes: 0

Related Questions