My Blog List

Tuesday, April 23, 2013

Spring Annotation Qualifier

@Autowired Annotation finds which bean is proper to set
if there are more than one bean, @Autowired don't know which bean is proper
so use @Qualifier to target the proper bean

HelloController class
public class Qualifier{
package com.sang.common.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/welcome")
public class HelloController {

 @Autowired
 @Qualifier("helloTwoWorld")
 private HelloWorld helloWorld;

 @RequestMapping(method = RequestMethod.GET)
 public String printWelcome(ModelMap model) {

  model.addAttribute("message", helloWorld.getName());
  return "hello";

 }

}
}
HelloWorld class

package com.sang.common.controller;

/**
 * Spring bean
 * 
 */
public class HelloWorld {
 private String name;

 public void setName(String name) {
  this.name = name;
 }

 /**
  * @author jjhangu @create 2013. 4. 24.
  * 
  * @return the name
  */
 public String getName() {
  return name;
 }

 public void printHello() {
  System.out.println("Spring 3 : Hello ! " + name);
 }
}
mvc-dispatcher-servlet.xml


 

 
  
   /WEB-INF/pages/
  
  
   .jsp
  
 
 
 


Qualifier.xml


      
 
   
    one
    
   
 
 
 
   
    two
    
   
 
 
 
Log
http://localhost:8080/SpringQualifier/welcome
you will see : Message : two

No comments:

Post a Comment