2

For a custom Scope (I cannot post here because of legal reasons) I need a custom BeanFactory that overrides the getBean(Class requiredType) method, like:

public class MyBeanFactory implements BeanFactory {

    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        if(MyScope.someSetting) {
            return useBeanA();
        } else {
            return useBeanB();
        }
    }
}

This BeanFactory must be used in my whole spring container for getting beans (by type). How can I inject it in the ApplicationContext (or do I need a custom ApplicationContext)?

I cannot use a FactoryBean, because the logic is not special to one (or a few) bean(s). I cannot use a InstantiationAwareBeanPostProcessor because its postProcessBeforeInstantiation() method is called only onced.

t777
  • 3,099
  • 8
  • 35
  • 53
  • Isn't this something that should be handled only by the scope of the bean? So if your problem really is applying a scope to all beans instead of the normal singleton scope, than maybe it would be a better idea to have a look at how you achieve this. What kind of application context are you using or is it required to be a generic solution? – SpaceTrucker Apr 28 '17 at 11:48
  • My custom scope is applied only to some beans, not all. That's why I need some modification of the instantiation / selection logic. I am using the `AnnotationConfigWebApplicationContex` – t777 Apr 28 '17 at 11:51
  • 1
    But can't your custom scope just do what you are currently trying to achieve in `MyBeanFactory.getBean` in its method own `MyCustomScope.get(String, ObjectFactory>)`? – SpaceTrucker Apr 28 '17 at 11:59
  • Thanks. I now see, what you mean. I will try it ... – t777 Apr 28 '17 at 12:00
  • Currently I just call `objectFactory.getObject()` and unfortunately this is the only method of `ObjectFactory`. I may cast it to `BeanFactory` to get other beans, but I am not sure, if this is a good idea? – t777 Apr 28 '17 at 12:07
  • How about making you scope `ApplicationContextAware`? – SpaceTrucker Apr 28 '17 at 12:32
  • I tried that as I tried to autowire the `ApplicationContext`. Both does not work. The `ApplicationContext` gets not injected. – t777 Apr 28 '17 at 12:46
  • I was wrong. It gets injected, but too late. – t777 Apr 28 '17 at 12:48
  • I injected a `BeanFactory` by the constructor of the `Scope`. That works. Thank you! – t777 Apr 28 '17 at 15:17

1 Answers1

1

As suggested by 'spacetrucker' (see the comments to the question), I solved the problem quite different. I added my bean instantiation / selection logic to my custom Scope and injected a BeanFactory by the constructor to this Scope.

t777
  • 3,099
  • 8
  • 35
  • 53