Announcement Announcement Module
Collapse
No announcement yet.
Inject different service instance into controller Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Inject different service instance into controller

    Hi All,

    I have the following Controller and Service

    Code:
    @Controller
    public class MyController
    {
         @Autowired
         private MyService myService;
    
        @RequestMapping(method=RequestMethod.GET, value="/connect.do")
        public String connect(Model model)
        {
            invokeService();
            return  "xxx";
        }
    
         private void invokeService()
         {
                myService.test();
          }
    
    }
    Code:
    @Service
    public class MyService
    {
         private int value1 = 200;
         private int value2 = 333;
         private String value3 ;
         private String value4 ;
         private String value5 ;
         ....
    
         public void test()
         {
                System.out.println(value1++);
                foo();
          }
    
         private void foo()
         {
              
         }
    
    }
    When I use 2 browsers to connect to the application, the output is "200" and "201", which means Spring inject the same MyService instance into the controller for different connection.

    I need the output to be "200" and "200" when I use 2 different connections to access the application, because I need to share values1, values2, value3, etc between "test()" and "foo()". How to do it in Spring? Basically, I want Spring to inject different instance for different connection. I tried @Scope("prototype") in Service bean and it doesn't work.


    I can make it work by using:
    Code:
    @Controller
    public class MyController
    {
    
         private void invokeService()
         {
                new MyService.test();
          }
    
    }
    I am just wondering that how to do it in Spring. Any help will be appreciated
    Last edited by wlin; Aug 16th, 2012, 09:55 AM.

  • #2
    Another way of asking this question is: How to have multiple controller instances (one for each user connection) as opposed to one controller instance serving for all connections?
    Last edited by wlin; Aug 16th, 2012, 09:57 AM.

    Comment


    • #3
      I made it work by using @Scope( "prototype" ) on both MyController and MyService, and "@Autowired MyService myService"

      Comment

      Working...
      X