Spring 自动装配 byType,通过属性的 type 与配置文件中的 beans 进行匹配和连接,匹配成功,注入 bean ,否则,抛出异常
    案例代码:
    Person.java

    1. package com.baklib.custom;
    2. public class Person {
    3. private String name;
    4. private int age;
    5. public String getName() {
    6. return name;
    7. }
    8. public void setName(String name) {
    9. this.name = name;
    10. }
    11. public int getAge() {
    12. return age;
    13. }
    14. public void setAge(int age) {
    15. this.age = age;
    16. }
    17. }

    Car.java

    1. package com.baklib.custom;
    2. public class Car {
    3. private String name;
    4. private double price;
    5. public String getName() {
    6. return name;
    7. }
    8. public void setName(String name) {
    9. this.name = name;
    10. }
    11. public double getPrice() {
    12. return price;
    13. }
    14. public void setPrice(double price) {
    15. this.price = price;
    16. }
    17. }

    Action.java

    1. package com.baklib.custom;
    2. public class Action {
    3. private Person person;
    4. private Car car;
    5. public Person getPerson() {
    6. return person;
    7. }
    8. public void setPerson(Person person) {
    9. this.person = person;
    10. }
    11. public Car getCar() {
    12. return car;
    13. }
    14. public void setCar(Car car) {
    15. this.car = car;
    16. }
    17. public void buyCar() {
    18. System.out.println(person.getName()+"今年"+person.getAge()+"岁,花了"
    19. +car.getPrice()+"元买了"+car.getName());
    20. }
    21. }

    MainApp.java

    1. package com.baklib.custom;
    2. import org.springframework.context.ApplicationContext;
    3. import org.springframework.context.support.ClassPathXmlApplicationContext;
    4. public class MainApp {
    5. public static void main(String[] args) {
    6. ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    7. Action action = (Action) context.getBean("action");
    8. action.buyCar();
    9. }
    10. }

    配置文件 Beans.xml

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    5. <bean id="action" class="com.baklib.custom.Action" autowire="byType">
    6. </bean>
    7. <bean id="person" class="com.baklib.custom.Person">
    8. <property name="name" value="张三" />
    9. <property name="age" value="20" />
    10. </bean>
    11. <bean id="car" class="com.baklib.custom.Car">
    12. <property name="name" value="小轿车" />
    13. <property name="price" value="100000" />
    14. </bean>
    15. </beans>

    编写完以上代码,就可以运行这个程序,运行结束后,可以在控制台看到下面的信息

    1. 张三今年20岁,花了100000.0元买了小轿车