zakmck
zakmck

Reputation: 3024

How to inject a custom ObjectFactory in Spring

I'm injecting an ObjectFactory into a bean, to get a new object when required, like it is done in here (see the accepted answer).

Now I need to start using a custom ObjectFactory, which gets a new object from the ApplicationContext and also does something else. Something like this:

@Component
public class MyDefenderObjectFactory implements ObjectFactory<Defender>, ApplicationContextAware
{
  private ApplicationContext appCtx;

  @Override
  public Defender getObject () throws BeansException
  {
    // Some other operation we need to run upon new object creation
    System.out.println ( "New Defender being returned" );
    return this.appCtx.getBean ( Defender.class );
  }

  @Override
  public void setApplicationContext ( ApplicationContext applicationContext ) throws BeansException
  {
    this.appCtx = applicationContext;
  }
}

My hope is that this factory is injected into the defenderFactory from the example linked above:

@Component
class DefenderBuilder implement VechicleBuilder 
{
  @Autowired
  ObjectFactory<Defender> defenderFactory;

  Defender build() {
     return defenderFactory.getObject()
  }
}

@Component @Scope("prototype")
class Defender {
...
}

However, Spring isn't using this class to inject an ObjectFactory bean into defenderFactory. How can it be done? I've also tried to add @Qualifier ( "MyDefenderObjectFactory" ) to the field defenderFactory above, but no luck.

Upvotes: 3

Views: 7161

Answers (1)

Oleg
Oleg

Reputation: 6324

As you can see here ObjectFactory resolution is hard coded and handled by Spring internally:

else if (ObjectFactory.class == descriptor.getDependencyType()) {
    return new DependencyObjectFactory(descriptor, beanName);
}

This means you can't get MyDefenderObjectFactory when you resolve by type, you can get it if you will resolve by name and for that you need to use the Resource annotation which resolves by name first:

@Resource(name="myDefenderObjectFactory")   
ObjectFactory<Defender> defenderFactory;

Upvotes: 4

Related Questions