Spring 框架依赖注入

IOC:某一接口具体实现类的控制权从控制类中移除,转交给第三方(如Spring)

三种依赖注入的方式

  1. 属性注入,通过setter方法注入bean的属性值或依赖的对象
  2. 构造注入
  3. 工厂方法注入(很少使用)

例子

这里我们使用了spring-4.3.2,maven配置文件

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${org.springframework-version}</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<!-- Junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
</dependency>

一. 属性注入和构造方法注入

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:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 
        配置bean
        id:标识容器中bean对象
        class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean类必须有无参构造器
     -->
    <bean id="helloWorld" class="com.spring.test.HelloWorld">
        <property name="name" value="crystal"></property>
    </bean>

    <!-- 通过构造方法配置bean,可以指定参数的位置和类型,以区分重载的构造函数 -->
    <bean id="car" class="com.spring.test.Car">
        <constructor-arg value="BENCHI" index="0"></constructor-arg>
        <constructor-arg value="200000.0" index="1" type="double"></constructor-arg>
    </bean>
    <bean id="car1" class="com.spring.test.Car">
        <!-- 如果字面值包含特殊字符,使用<![CDATA[]]>包裹起来
            属性值可以使用value子节点来配置
         -->
        <constructor-arg type="java.lang.String">
            <value><![CDATA[<shanghai>]]></value>
        </constructor-arg>
        <constructor-arg value="200" index="1" type="int"></constructor-arg>
    </bean>

    <bean id="person" class="com.spring.test.Person">
        <property name="name" value="Crystal"></property>
        <property name="age" value="20"></property>
        <!-- 可以使用ref建立引用之间的关系 -->
        <!-- 
        <property name="car" ref="car"></property>
         -->
        <!-- 
            <property name="car">
                <ref bean="car2"/>
            </property>
         -->
         <!-- 
         <property name="car">
            <bean class="com.spring.test.Car">
                <constructor-arg value="changanFute"></constructor-arg>
                <constructor-arg value="3000000"></constructor-arg>
                <constructor-arg value="240"></constructor-arg>
            </bean>
         </property> 
         -->
         <!-- 测试赋值null -->
         <!-- <property name="car"><null/></property> -->
         <property name="car" ref="car1"></property>
         <!-- 为级联属性赋值,注意:属性需要先初始化后才能为级联属性赋值,和structs2不同 -->
         <property name="car.price" value="400000"></property>
    </bean>

    <!-- 测试配置集合属性 -->
    <bean id="person3" class="com.spring.test.collections.Person">
        <property name="name" value="barry"></property>
        <property name="age" value="21"></property>
        <property name="cars">
            <list>
                <ref bean="car"/>
                <ref bean="car1"/>
                <bean class="com.spring.test.Car">
                    <constructor-arg value="changanFute"></constructor-arg>
                    <constructor-arg value="3000000"></constructor-arg>
                    <constructor-arg value="240"></constructor-arg>
                </bean>
            </list>
        </property>
    </bean>

    <!-- 配置Map的属性值 -->
    <bean id="newPerson" class="com.spring.test.collections.NewPerson">
        <property name="name" value="lina"></property>
        <property name="age" value="22"></property>
        <property name="cars">
            <!-- 使用map节点及map的entry子节点配置Map类型的成员变量 -->
            <map>
                <entry key="AA" value-ref="car"></entry>
                <entry key="BB" value-ref="car1"></entry>
            </map>
        </property>
    </bean>


    <!-- 配置Properties属性值 -->
    <bean id="dataSource" class="com.spring.test.collections.DataSource">
        <property name="properties">
            <!-- 使用props和prop子节点来为Properties属性赋值 -->
            <props>
                <prop key="user">root</prop>
                <prop key="password">1234</prop>
                <prop key="jdbcUrl">jdbc:mysql://test</prop>
                <prop key="jdbcDriver">com.mysql.jdbc.Driver</prop>
            </props>
        </property>
    </bean>

    <!-- 配置单例的集合bean,以供多个bean进行引用,需要导入util命名空间 -->
    <util:list id="cars">
        <ref bean="car"/>
        <ref bean="car1"/>
    </util:list>

    <bean id="person4" class="com.spring.test.collections.Person">
        <property name="name" value="Jackie"></property>
        <property name="age" value="30"></property>
        <property name="cars" ref="cars"></property>
    </bean>

    <!-- 通过p命名空间为bean的属性赋值,需要先导入p命名空间,相对于传统配置方式更为简洁 -->
    <bean id="person5" class="com.spring.test.collections.Person" p:name="Queue" p:age="32" p:cars-ref="cars"></bean>
</beans>

1. 下面是简单的属性注入、构造注入的测试类

Car.java

package com.spring.test;

public class Car {
    private String name;
    private int maxSpeed;
    private double price;

    public Car() {
    }

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public Car(String name, int maxSpeed) {
        this.name = name;
        this.maxSpeed = maxSpeed;
    }

    public Car(String name, double price, int maxSpeed) {
        this.name = name;
        this.price = price;
        this.maxSpeed = maxSpeed;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car [name:" + name + ", price:" + price + ", maxSpeed:" + maxSpeed + "]";
    }
}

HelloWorld.java

package com.spring.test;

public class HelloWorld {

    private String name;

    public HelloWorld() {
        System.out.println("HelloWorld constructor...");
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        System.out.println("setName:" + name);
        this.name = name;
    }

    @Override
    public String toString() {
        return "hello," + name;
    }
}

Person.java

package com.spring.test;

public class Person {

    private String name;
    private int age;
    private Car car;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Person: [name=" + name + ", age=" + age + ", car=" + car + "]";
    }
}

Main.java

package com.spring.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        HelloWorld hello = new HelloWorld();
        hello.setName("barry");
        System.out.println("print:"+ hello + "\n");

        // 装入 Spring 配置文件
        /**
         * 装入 Spring 配置文件
         * ApplicationContext是IOC容器,它有两个主要实现类(ClassPathXmlApplicationContext和FileSystemXmlApplicationContext)
         * ApplicationContext在初始化上下文时就实例化所有单例的Bean
         */
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //HelloWorld hello1 = (HelloWorld) context.getBean("helloWorld");   // 通过id获取bean对象
        HelloWorld hello1 = context.getBean(HelloWorld.class);  // 通过类型获取bean对象(要求在IOC容器里该类型的对象只能有一个)
        System.out.println(hello1);
    }

    @Test
    public void testContructor() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Car car = (Car) context.getBean("car"); // 通过类型获取bean对象(要求在IOC容器里该类型的对象只能有一个)
        Car car1 = (Car) context.getBean("car1");
        System.out.println(car);
        System.out.println(car1);

        Person person = (Person) context.getBean("person");
        System.out.println(person);
    }
}

2. 下面是集合的测试类
NewPerson.java

package com.spring.test.collections;

import java.util.Map;

import com.spring.test.Car;

public class NewPerson {

    private String name;
    private int age;
    private Map<String, Car> cars;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Map<String, Car> getCars() {
        return cars;
    }
    public void setCars(Map<String, Car> cars) {
        this.cars = cars;
    }

    @Override
    public String toString() {
        return "Person: [name=" + name + ", age=" + age + ", cars=" + cars + "]";
    }
}

Person.java

package com.spring.test.collections;

import java.util.List;

import com.spring.test.Car;

public class Person {

    private String name;
    private int age;
    private List<Car> cars;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public List<Car> getCars() {
        return cars;
    }
    public void setCars(List<Car> cars) {
        this.cars = cars;
    }

    @Override
    public String toString() {
        return "Person: [name=" + name + ", age=" + age + ", cars=" + cars + "]";
    }
}

DataSource.java

package com.spring.test.collections;

import java.util.Properties;

public class DataSource {

    private Properties properties;

    public Properties getProperties() {
        return properties;
    }
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "DataSource: [properties:" + properties + "]";
    }
}

Main.java

package com.spring.test.collections;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    @Test
    public void testCollections() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Person person = (Person) context.getBean("person3");
        System.out.println(person);

        NewPerson newPerson = (NewPerson) context.getBean("newPerson");
        System.out.println(newPerson);

        DataSource dataSource = (DataSource) context.getBean("dataSource");
        System.out.println(dataSource);

        Person person4 = (Person) context.getBean("person4");
        System.out.println(person4);

        Person person5 = (Person) context.getBean("person5");
        System.out.println(person5);
    }
}

二. 下面静态工厂方法和实例工厂方法注入的实例

beans-factory.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 
        通过静态工厂方法来配置bean,注意不是配置静态工厂方法实例,而是配置bean实例 
        class:指向静态方法的全类名
        factory-method:指向静态工厂方法名
        constructor-arg:如果工厂方法需要传入参数,则使用 constructor-arg 来配置参数
    -->
    <bean id="car" class="com.spring.test.factory.StaticBeanFactory" factory-method="getCar">
        <constructor-arg value="audi"></constructor-arg>
    </bean>

    <!-- 
        通过实例工厂方法来配置bean 
        factory-method:指向工厂方法名
        factory-bean:指向拥有该工厂方法的bean
        constructor-arg:如果工厂方法需要传入参数,则使用 constructor-arg 来配置参数
    -->
    <bean id="factory" class="com.spring.test.factory.InstanceCarFactory"></bean>
    <bean id="car1" class="com.spring.test.factory.Car" factory-bean="factory" factory-method="getCar">
        <constructor-arg value="ford"></constructor-arg>
    </bean>
</beans>

Car.java

package com.spring.test.factory;

public class Car {
    private String brand;
    private double price;

    public Car(String brand, double price) {
        super();
        this.brand = brand;
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Car [brand=" + brand + ", price=" + price + "]";
    }
}

StaticBeanFactory.java

package com.spring.test.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * 静态工厂方法:直接调用某一个类的静态方法就可以获取 Bean 实例
 * @author cye
 *
 */
public class StaticBeanFactory {

    private static Map<String, Car> cars = new HashMap<String, Car>();
    static {
        cars.put("audi", new Car("audi", 200000));
        cars.put("ford", new Car("ford", 300000));
    }

    public static Car getCar(String brand) {
        return cars.get(brand);
    }
}

InstanceCarFactory.java

package com.spring.test.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * 实例工厂方法:将对象的创建过程封装到另一个对象实例的方法里,当客户端需要请求对象时,只需要简单调用实例方法而不需要关心对象具体的创建细节,
 * @author cye
 *
 */
public class InstanceCarFactory {

    private Map<String, Car> cars;

    public InstanceCarFactory() {
        cars = new HashMap<String, Car>();
        cars.put("audi", new Car("audi", 200000));
        cars.put("ford", new Car("ford", 300000));
    }

    public Car getCar(String brand) {
        return cars.get(brand);
    }
}

Main.java

package com.spring.test.factory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml");
        Car car = (Car) ctx.getBean("car");
        System.out.println(car);

        car = (Car) ctx.getBean("car1");
        System.out.println(car);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值