arahant
arahant

Reputation: 2203

Spring configuration calling more than one method

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

Upvotes: 0

Views: 504

Answers (1)

Vikdor
Vikdor

Reputation: 24134

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 @Configurable annotation to inject such domain objects that are created using new operator. 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

  • define a bean of type MyContext
  • Create a MyEntityFactory class that would depend on the MyContext bean.
  • The factory method would take the MyContext bean as argument, calls context.start() on it and returns an instance of MyEntity.
  • You would define the MyEntity bean using this factory class.

The MyEntityFactory class would be as follows:

public class MyEntityFactory
{
    public static MyEntity getMyEntity(MyContext context)
    {
        context.start();
        return context.getEntity();
    }
}

The spring bean configuration will be as follows:

<bean id="myContext" class="FQCN.Of.MyContext" />
<bean id="myEntity" class="FQCN.Of.MyEntityFactory" factory-method="getMyEntity">
    <constructor-arg ref="myContext" />
</bean>

Since MyEntity is a singleton bean, the factory method will be called only once, btw.

More on creating beans using factory methods here.

Upvotes: 2

Related Questions