Announcement Announcement Module
No announcement yet.
"factory method" returning an interface? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • "factory method" returning an interface?


    I have a factory that creates different sub-classes depending on configuration. For example if might return either "EnglishComparator" or "ChineseComparator":

    interface Comparator {
    class MyFactory{
    public Comparator createComparator(){
    if... return new EnglishComparator();
    else... return new ChineseComparator();

    Now, I wanted to declare this 'comparator' as a spring bean, with "class=Comparator" (because on the one hand I want it to be clear that it's "comparator", on the other hand I can't tell the exact concrete type).
    <bean name="defaultComp" class="Comparator" factory-bean="f1" factory-method="createComparator" />

    Unfortunately, my intellij plugin won't allow it, it expects a class (rather than interface). Is it an bug in the plugin, or is it really a design decision of Spring? My programmer's intuition was to allow that...


  • #2
    Please use [ code][/code ] tags when posting code, after you have done that I suggest you read the reference guide on FactoryBean and using factory methods.

    If you use a factory method you shouldn't specify a class...


    • #3
      Thanks, but that was my question -

      Thanks, I've read the reference guide, but was wondering whether I've missed something:
      From the perspective of design/readability/validation, I expected an option to declare the type of a component, even when retrieved through a factory. Something like (assuming my bean is of type Comparator) :
      Dummy code warning: "bean-type" is not a real spring tag
      <bean ... factory-method="create"  bean-type="java.util.Comparator"/>
      Is it not supported by spring?
      Admittedly it's not a "show stopper", but I wanted to make sure I'm not missing something. Thanks.


      • #4
        That isn't supported. The ApplicationContext/BeanFactory knows that something is a FactoryBean, it then uses reflection to detect the type of object returned. So you do not have to specify it yourself.


        • #5

          Thanks for this clarification.