需求:在Person类中注入Car类
分析:
xml中定义Car和Person
Person中用注解注入Car
applicationContext.xml:
<?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"
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">
<!--开启注解功能-->
<context:annotation-config/>
<bean name="car" class="annotation.Car"></bean>
<bean name="person" class="annotation.Person"></bean>
</beans>
Car:
public class Car {
public Car() {
System.out.println("car被实例化了");
}
}
Person:
public class Person {
private String name;
//注解注入
@Autowired
@Qualifier("car")
private Car car;
public Person() {
}
public Person(Car car) {
this.car = car;
System.out.println("Person被实例化了");
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", car=" + car +
'}';
}
}
测试类
public class test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person) ac.getBean("person");
System.out.println("person = " + person);
((ClassPathXmlApplicationContext) ac).close();
}
}