Results 1 to 3 of 3

Thread: Inject different service instance into controller

  1. #1
    Join Date
    Jul 2012
    Posts
    11

    Default 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 at 08:55 AM.

  2. #2
    Join Date
    Jul 2012
    Posts
    11

    Default

    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 at 08:57 AM.

  3. #3
    Join Date
    Jul 2012
    Posts
    11

    Default

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

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •