Spring属性注入方式详解(附源码剖析)
一、什么是Spring属性注入
在Java中,万物皆对象,属性注入就是在实例化对象时,同时向对象中的属性进行相应的赋值。通俗点说,属性注入就是给类中的属性赋值。
二、属性注入的几种方式
对于类成员变量来说,注入方式有三种: 1.setter方式注入 2.构造函数注入 3.接口注入
对于Spring来说,Spring支持前面两种,并且还支持: 1.p名称空间注入 2.spel属性注入 3.复杂类型注入
三、属性注入举例
第一种:setter方式注入 1.创建一个SpringBoot项目 2.编写一个Book.java类,如下:
package com.mango.properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component /*@PropertySource("classpath:book.properties")*/ public class Book { @Value("${book.id}") private long id; @Value("${book.name}") private String name; @Value("${book.author}") private String author; @Override public String toString() { return "Book{" + "id=" + id + ", name=" + name + + ", author=" + author + + }; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }
3.在创建SpringBoot项目时自动生成的application.properties中添加如下内容:
book.id=1 book.name=三国演义 book.author=罗贯中
4.编写测试类PropertiesApplicationTests.java,如下:
package com.mango.properties; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class PropertiesApplicationTests { @Autowired Book book; @Test void contextLoads() { System.err.println(book); } }
5.运行结果:
Book{ id=1, name=三国演义, author=罗贯中}
注意事项: 1.若使用自己创建的xxx.properties文件进行上述方式进行属性注入(注入内容与上述第3步相同),需要在Book.java上进行添加如下注解:
@PropertySource("classpath:book.properties")
注:此注解就是指定自己创建的xxx.properties文件
完整代码如下所示:
package com.mango.properties; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @PropertySource("classpath:book.properties") public class Book { @Value("${book.id}") private long id; @Value("${book.name}") private String name; @Value("${book.author}") private String author; @Override public String toString() { return "Book{" + "id=" + id + ", name=" + name + + ", author=" + author + + }; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } }