Announcement Announcement Module
Collapse
No announcement yet.
@Autowired setter Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • @Autowired setter

    Hi

    Using the @Autowired annotation, spring can set bean property without setter.
    Can we do the samething with the java code.

    I would like to change injected service with mockservice for unit test.

    Regards

  • #2
    do you want to do this without using spring ?

    Comment


    • #3
      Have you got a solution

      Hi

      I just want to do this without declaring getter and setter all the time.

      Regards

      Comment


      • #4
        You have to delclare interface then as type.

        @Autowired
        MyService service; --> MyService is interface where as in your xml you

        defind bean with implementation of Myservice


        it will work with interface not with concrete type.

        @Autowired
        MyServiceImpl serviceImpl will not work if MyServiceImpl is Concrete class

        Comment


        • #5
          Misunderstood

          Hi

          Take this example:
          Code:
          @Controller
          @RequestMapping("/user/")
          Class UserController
          {
          	@Autowired
          	private UserService userService;
          
          	@RequestMapping(value = "/list")
          	public void listUser(ModelMap model)
          	{
          		model.addAttribute("users", userService.getUsers());
          	}
          }
          When testing the user controller I will have the real userService.
          I cam create a mock service with easymock

          Code:
          mockUserService = EasyMock.createMock(UserService.class);
          EasyMock.expect(mockUserService.getUsers()).andReturn(new ArrayList());
          the mockUserService is the fake service that will return an empty arraylist when its getUsers() is call.

          I want to inject that mockUserService to the UserController.
          Is it possible to do so without using setter ?

          Comment


          • #6
            Autowire will not work unless you load the spring application context.
            bean you want to autowire in to variable or setter needs to defined in application context XML file.

            Then you load this application context without loading application context it will not work.

            Comment

            Working...
            X