Use @Qualifier comments and @Autowired comments by specifying which real bean will be assembled to eliminate clutter

Source: Internet
Author: User
Tags tutorialspoint

1. When you create multiple beans of the same type and want to assemble only one of them, in this case, you can use @Qualifier annotations and @Autowired annotations to configure them precisely.

2. Example

Java

 Public classStudent {PrivateInteger age; PrivateString name;  Public voidsetage (Integer age) { This. Age =Age ; }       PublicInteger getage () {returnAge ; }    Public voidsetName (String name) { This. Name =name; }      PublicString GetName () {returnname; }}
 public  class   profile {@Autowired @Qualifier ( "student1" ) private   Student Student;  public   profile () {System.out.println ( /span> "Inside profile constructor."   );  public  void   Printage () {System.out.println ( Age: "+ Student.getage ());  public  void   Printname () {System.out.println ( "Name:" + Student.getname ()); }}
 Public class Mainapp {   publicstaticvoid  main (string[] args) {      new Classpathxmlapplicationcontext ("Beans.xml");       = (profile) Context.getbean ("Profile");      Profile.printage ();      Profile.printname ();   }}

Beans.xml

<?XML version= "1.0" encoding= "UTF-8"?><Beans>   <Context:annotation-config/>
<BeanID= "Profile"class= "Com.tutorialspoint.Profile"></Bean>
<BeanID= "Student1"class= "Com.tutorialspoint.Student"> < Propertyname= "Name"value= "Zara" /> < Propertyname= "Age"value= "One"/> </Bean>

<BeanID= "Student2"class= "Com.tutorialspoint.Student"> < Propertyname= "Name"value= "Nuha" /> < Propertyname= "Age"value= "2"/> </Bean>
</Beans>

Print output

Inside profile constructor. Age:11name:zara

  

Use @Qualifier comments and @Autowired comments by specifying which real bean will be assembled to eliminate clutter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.