服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring框架依赖注入方法示例

Spring框架依赖注入方法示例

2021-02-20 11:30逆水行舟 Java教程

这篇文章主要介绍了Spring框架依赖注入方法示例,分享了三种方法示例,具有一定参考价值,需要的朋友可以了解下。

在阅读这篇文章之前,大家可以先参阅理解Spring中的依赖注入和控制反转一文,了解下依赖注入和控制反转的相关内容。

三种依赖注入的方式

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<dependency>
 <groupid>org.springframework</groupid>
 spring-core</artifactid>
 <version>${org.springframework-version}</version>
 <exclusions>
  <exclusion>
   <groupid>commons-logging</groupid>
   commons-logging</artifactid>
  </exclusion>
 </exclusions>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 spring-beans</artifactid>
 <version>${org.springframework-version}</version>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 spring-aop</artifactid>
 <version>${org.springframework-version}</version>
</dependency>
<dependency>
 <groupid>org.springframework</groupid>
 spring-context</artifactid>
 <version>${org.springframework-version}</version>
</dependency>
<dependency>
 <groupid>commons-logging</groupid>
 commons-logging</artifactid>
 <version>1.2</version>
</dependency>
<!-- Junit -->
<dependency>
 <groupid>junit</groupid>
 junit</artifactid>
 <version>3.8.1</version>
 <scope>test</scope>
</dependency>

applicationContext.xml配置文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<!--?xml version="1.0" encoding="UTF-8"?-->
<beans xmlns="https://www.springframework.org/schema/beans" xmlns:p="https://www.springframework.org/schema/p" xmlns:util="https://www.springframework.org/schema/util" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
  https://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd">
 
 <!--
  配置bean
  id:标识容器中bean对象
  class:bean的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean类必须有无参构造器
  -->
 <bean class="com.spring.test.HelloWorld" id="helloWorld">
  <property name="name" value="crystal"></property>
 </bean>
 
 <!-- 通过构造方法配置bean,可以指定参数的位置和类型,以区分重载的构造函数 -->
 <bean class="com.spring.test.Car" id="car">
  <constructor-arg index="0" value="BENCHI"></constructor-arg>
  <constructor-arg index="1" type="double" value="200000.0"></constructor-arg>
 </bean>
 <bean class="com.spring.test.Car" id="car1">
  <!-- 如果字面值包含特殊字符,使用<![CDATA[]]>包裹起来
   属性值可以使用value子节点来配置
   -->
  <constructor-arg type="java.lang.String">
   <value><!--[CDATA[<shanghai-->]]></value>
  </constructor-arg>
  <constructor-arg index="1" type="int" value="200"></constructor-arg>
 </bean>
 
 <bean class="com.spring.test.Person" id="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 class="com.spring.test.collections.Person" id="person3">
  <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>
   </ref></ref></list>
  </property>
 </bean>
 
 <!-- 配置Map的属性值 -->
 <bean class="com.spring.test.collections.NewPerson" id="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 class="com.spring.test.collections.DataSource" id="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">
 </ref></ref></util:list>
 
 <bean class="com.spring.test.collections.Person" id="person4">
  <property name="name" value="Jackie"></property>
  <property name="age" value="30"></property>
  <property name="cars" ref="cars"></property>
 </bean>
 
 <!-- 通过p命名空间为bean的属性赋值,需要先导入p命名空间,相对于传统配置方式更为简洁 -->
 <bean class="com.spring.test.collections.Person" id="person5" p:age="32" p:cars-ref="cars" p:name="Queue"></bean>
</beans>

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

Car.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
    }
}

总结

以上就是本文关于Spring框架依赖注入方法示例的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

原文链接:https://www.2cto.com/kf/201608/539381.html

延伸 · 阅读

精彩推荐