Announcement Announcement Module
No announcement yet.
Autowiring returns multiples instances for a singleton bean Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Autowiring returns multiples instances for a singleton bean


    Please ignore this thread, it's my bad. I mistakenly create two ApplicationContext that results some classes get the same bean from one context while others get from another.

    Spring does return the same bean for different interfaces as long as they are implemented by the same bean


    The title bar has strict chars limitation so I have to use such a name that is a little misleading.

    Actually the autowiring returns multiple instances for different interfaces which are all implemented by the same concrete class that is a singleton bean.

    public class Service implements ExternalInterface, InternalInterface {
                        ... ...
    public class Client { @Autowired ExternalInterface iface;}
    public class Framework { @Autowired InternalInterface iface;}
    As you can see, class Service exposes user method through ExternalInterface to client while it also contains intrinsic methods declared by InternalInterface that is only used by Framework. I do this for isolation on interface level. I expect Spring wries Client and Framework to the same instance of Service as it is a singleton bean. However, Spring returns different instances of Service. Though I understand this behavior as ExternalInterface and InternalInterface are essential different types, I am still wondering if there is a solution for such case, for one class implementing multiple interfaces is fairly common in Java.

    One solution I can see is using @Resource to autowire by name. However, I personally prefer by type to by name. As class type itself is quite nice meta data, it prevents typo of bean name from either xml file or java file.

    Does anybody have an idea here? thank you.
    Last edited by zx_wing; Mar 17th, 2012, 10:40 PM.