package com. xu. pojo ;
public class Cat {
public void shout ( ) {
System . out. println ( "miao~" ) ;
}
}
package com. xu. pojo ;
public class Dog {
public void shout ( ) {
System . out. println ( "wang~" ) ;
}
}
package com. xu. pojo ;
import org. springframework. beans. factory. annotation. Autowired ;
import org. springframework. beans. factory. annotation. Qualifier ;
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier ( value = "dog2" )
private Dog dog;
@Qualifier ( value = "旺财" )
private String name;
@Override
public String toString ( ) {
return "People{" +
"cat=" + cat +
", dog=" + dog +
", name='" + name + '\'' +
'}' ;
}
public Cat getCat ( ) {
return cat;
}
public void setCat ( Cat cat) {
this . cat = cat;
}
public Dog getDog ( ) {
return dog;
}
public void setDog ( Dog dog) {
this . dog = dog;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
}
< ? xml version= "1.0" encoding= "UTF-8" ? >
< beans xmlns= "http://www.springframework.org/schema/beans"
xmlns: xsi= "http://www.w3.org/2001/XMLSchema-instance"
xmlns: context= "http://www.springframework.org/schema/context"
xmlns: aop= "http://www.springframework.org/schema/aop"
xsi: schemaLocation= "http: / / www. springframework. org/ schema/ beans
http: / / www. springframework. org/ schema/ beans/ spring- beans. xsd
http: / / www. springframework. org/ schema/ context
http: / / www. springframework. org/ schema/ context/ spring- context. xsd
http: / / www. springframework. org/ schema/ aop
http: / / www. springframework. org/ schema/ aop/ spring- aop. xsd">
< ! -- 开启注解的支持-- >
< context: annotation- config/ >
< bean id= "cat" class = "com.xu.pojo.Cat" / >
< bean id= "dog" class = "com.xu.pojo.Dog" / >
< bean id= "dog2" class = "com.xu.pojo.Dog" / >
< bean id= "people" class = "com.xu.pojo.People" / >
< / beans>
import com. xu. pojo. People ;
import org. junit. Test ;
import org. springframework. context. ApplicationContext ;
import org. springframework. context. support. ClassPathXmlApplicationContext ;
public class MyTest {
@Test
public void test1 ( ) {
ApplicationContext context = new ClassPathXmlApplicationContext ( "beans.xml" ) ;
People people = context. getBean ( "people" , People . class ) ;
people. getCat ( ) . shout ( ) ;
people. getDog ( ) . shout ( ) ;
}
}