I have code which looks like the following:
MyContext context = new MyContext();
context.start();
MyEntity entity = context.getEntity();
I want to inject the MyEntity instance into various classes.
But I don’t know how to setup my Spring configuration, where I first create an object, then call a method on it and then finally call another method which returns the entity I want to inject.
EDIT 2 – removed the Strings altogether
The most common type of dependencies injected using Spring don’t depend on the user input for their construction. This includes data access objects, services etc.,
You are talking about injecting domain objects whose construction depends on the user input either directly or indirectly.
Spring provides
@Configurableannotation to inject such domain objects that are created usingnewoperator. You can search for “@Configurable Domain Driven Design” on the internet to get examples of how this can be implemented. I myself used it in one my applications and wrote a simple post here that might help you get started.Edit:
To create a bean of type MyEntity as per the specification in your updated question, you would need to
context.start()on it and returns an instance of MyEntity.The MyEntityFactory class would be as follows:
The spring bean configuration will be as follows:
Since
MyEntityis a singleton bean, the factory method will be called only once, btw.More on creating beans using factory methods here.