spring中ioc_-Small Spring IOC篇:属性注入和使用XML资源注册Bean - j &lt

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多帮助力 👁️ 123 次阅读

一、前言

这一节我们将实现属性注入。

看到这里可能会有疑惑,前面不是已经对有参构造注入进行实现了吗?既然这些属性都能够注入进去了,为啥我们还要单独新增一个属性注入呢?

这是因为 Spring 不只支持“构造器传参”这一种方式,我们日常写业务代码的时候,我们见过两种场景,一种是自己新增一个有参构造,另一种是用 @Resource 来标记属性。

这两种注入方式都很常见,在课程中我们更多看到的是后者,而前者是 Spring 推崇的注入方式。因此这两种方式我们都有必要实现,这一节就是讲后者如何实现的。

另外,我们将用XML的格式来注册Bean,因此还会做这样的资源加载器。

二、属性注入

先了解原理:和上一节一样,本质还是通过反射来注入,只是上一节注入的是构造器,这一节直接注入属性。

首先还是先看看整体架构设计:

small-spring-step-04

└── src

├── main

│ └── java

│ └── cn.bugstack.springframework.beans

│ ├── factory

│ │ ├── config

│ │ │ ├── BeanDefinition.java

│ │ │ ├── BeanReference.java

│ │ │ └── SingletonBeanRegistry.java

│ │ ├── support

│ │ │ ├── AbstractAutowireCapableBeanFactory.java

│ │ │ ├── AbstractBeanFactory.java

│ │ │ ├── BeanDefinitionRegistry.java

│ │ │ ├── CglibSubclassingInstantiationStrategy.java

│ │ │ ├── DefaultListableBeanFactory.java

│ │ │ ├── DefaultSingletonBeanRegistry.java

│ │ │ ├── InstantiationStrategy.java

│ │ │ └── SimpleInstantiationStrategy.java

│ │ └── BeanFactory.java

│ ├── BeansException.java

│ ├── PropertyValue.java

│ └── PropertyValues.java

└── test

└── java

└── cn.bugstack.springframework.test

├── bean

│ ├── UserDao.java

│ └── UserService.java

└── ApiTest.java

1.BeanReference

首先这一节需要新增一个类:BeanReference,这个类用于承载依赖的bean的信息,也就是假如一个类中依赖了另一个bean(一个属性是另一个bean),那么这个属性的值就应该是bean的引用,也就可以归于beanReference对象了。

这个类中只有一个属性——beanName:

public class BeanReference {

private String beanName;

public BeanReference(String beanName) {

this.beanName = beanName;

}

public String getBeanName() {

return beanName;

}

}

2.定义属性

属性为啥要用一个类来承载呢?因为后期我们不止需属性名,还可能需要属性的其他信息,比如是公开还是私有等等,总而言之,这个 PropertyValue 就是用于承载属性的所有信息的对象。

public class PropertyValue {

private String name;

private Object value;

public PropertyValue(String name, Object value) {

this.name = name;

this.value = value;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Object getValue() {

return value;

}

public void setValue(Object value) {

this.value = value;

}

}

而一个类中当然可能会有很多属性,因此我们应该把这些属性单独放到一个集合中去。

但是又有个问题了,明明论查询Map会更快,这里为啥选择使用List作为容器呢?。

首先使用Map是可以的,这个地方只是用一个容器装载属性值,从原理上讲,使用任何容器都可以。

那为啥使用List呢?

因为Spring源码中就是用的List。这里只想表示 PropertyValues 是装载属性值的集合,没有强调查询速度。

List为啥够用?

因为一个类中的属性不会太多,通常也就5~20个,所以用遍历查询的性能消耗不大。

为啥使用遍历查询?

因为使用其他的算法没有意义,这个List本身不具备任何结构规律,因此用二分查找、双指针都没有意义。

public class PropertyValues {

ListpropertyValueList = new ArrayList<>();

public void addPropertyValue(PropertyValue pv) {

this.propertyValueList.add(pv);

}

public PropertyValue[] getPropertyValues() {

return this.propertyValueList.toArray(new PropertyValue[0]);

}

public PropertyValue getPropertyValue(String propertyName) {

for (PropertyValue pv : this.propertyValueList) {

if (pv.getName().equals(propertyName)) {

return pv;

}

}

return null;

}

}

3.BeanDefinition

新增 propertyValues 属性。

BeanDefinition本身就是用于描述Bean的类的信息,前面的Class对象是类的信息,类中的属性当然也是类的信息,因此我们新增 propertyValues 。

public class BeanDefinition {

private Class beanClass;

private PropertyValues propertyValues;

public BeanDefinition(Class beanClass, PropertyValues propertyValues) {

this.beanClass = beanClass;

this.propertyValues = propertyValues != null ? propertyValues : new PropertyValues();

}

public BeanDefinition(Class beanClass) {

this.beanClass = beanClass;

this.propertyValues = new PropertyValues();

}

public Class getBeanClass() {

return beanClass;

}

public void setBeanClass(Class beanClass) {

this.beanClass = beanClass;

}

public PropertyValues getPropertyValues() {

return propertyValues;

}

public void setPropertyValues(PropertyValues propertyValues) {

this.propertyValues = propertyValues;

}

}

4.createBean

在 AbstractAutowireCapableBeanFactory 中,这个类由于是作为骨架规定流程的,所以我们现在要新增一个bean填充属性的步骤了。

从这个步骤可以看到

@Override

protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {

Object bean = null;

try {

bean = createBeanInstance(beanDefinition, beanName, args);

// 给 Bean 填充属性

applyPropertyValues(beanName, bean, beanDefinition);

} catch (Exception e) {

throw new BeansException("Instantiation of bean failed", e);

}

addSingleton(beanName, bean);

return bean;

}

实现如下:

/**

* Bean 属性填充

*/

protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {

try {

PropertyValues propertyValues = beanDefinition.getPropertyValues();

for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {

String name = propertyValue.getName();

Object value = propertyValue.getValue();

if (value instanceof BeanReference) {

// A 依赖 B,获取 B 的实例化

BeanReference beanReference = (BeanReference) value;

value = getBean(beanReference.getBeanName());

}

// 属性填充

BeanUtil.setFieldValue(bean, name, value);

}

} catch (Exception e) {

throw new BeansException("Error setting property values:" + beanName);

}

}

这里就需要注意了,假如在我们开发中,一个类的属性被注解@Resource标记,同时又使用了有参构造器注入,那么就会触发两次注入流程,一次是createBeanInstance,一次是applyPropertyValues,但是实际开发中这样做并不会报错,而且最后的效果是一致的,只是会多一次注入流程,增加开销罢了。

5.测试

public class UserDao {

private static MaphashMap = new HashMap<>();

static {

hashMap.put("10001", "小傅哥");

hashMap.put("10002", "八杯水");

hashMap.put("10003", "阿毛");

}

public String queryUserName(String uId) {

return hashMap.get(uId);

}

}

注意,下面UserService就不用写构造器了,我们需要测试属性注入:

public class UserService {

private String uId;

private UserDao userDao;

public void queryUserInfo() {

System.out.println("查询用户信息:" + userDao.queryUserName(uId));

}

}

@Test

public void test_BeanFactory() {

// 1.初始化 BeanFactory

DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

// 2. UserDao 注册

beanFactory.registerBeanDefinition("userDao", new BeanDefinition(UserDao.class));

// 3. UserService 设置属性[uId、userDao]

PropertyValues propertyValues = new PropertyValues();

propertyValues.addPropertyValue(new PropertyValue("uId", "10001"));

propertyValues.addPropertyValue(new PropertyValue("userDao",new BeanReference("userDao")));

// 4. UserService 注入bean

BeanDefinition beanDefinition = new BeanDefinition(UserService.class, propertyValues);

beanFactory.registerBeanDefinition("userService", beanDefinition);

// 5. UserService 获取bean

UserService userService = (UserService) beanFactory.getBean("userService");

userService.queryUserInfo();

}

其中这一步就相当于 SpringBoot 的 @Resource 注解,但是这是扫描后的结果,而扫描部分我们还暂时没有实现。后面先会用 xml 配置,最后再实现注解扫描。

// 3. UserService 设置属性[uId、userDao]

PropertyValues propertyValues = new PropertyValues();

propertyValues.addPropertyValue(new PropertyValue("uId", "10001"));

propertyValues.addPropertyValue(new PropertyValue("userDao",new BeanReference("userDao")));

三、解析XML并注册Bean

这一部分内容属于Spring的core包的io部分,专门就是用来解析XML的。

如果一开始就只学了SpringBoot的人,可能都不知道这种原始的方式了,SSM框架在以前都是要通过XML配置的,SpringBoot就是简化了这个流程,直接面向注解开发了,所以当初跳过SSM可能学起来就有点吃力了。

首先看看我们希望把哪部分放到XML中配置:

还是先从架构设计入手,可以看到这次新增了很多类和接口,预示着后面内容可能要爆炸增长了。

small-spring-step-05

└── src

├── main

│ └── java

│ └── cn.bugstack.springframework

│ ├── beans

│ │ ├── factory

│ │ │ ├── config

│ │ │ │ ├── AutowireCapableBeanFactory.java

│ │ │ │ ├── BeanDefinition.java

│ │ │ │ ├── BeanReference.java

│ │ │ │ ├── ConfigurableBeanFactory.java

│ │ │ │ └── SingletonBeanRegistry.java

│ │ │ ├── support

│ │ │ │ ├── AbstractAutowireCapableBeanFactory.java

│ │ │ │ ├── AbstractBeanDefinitionReader.java

│ │ │ │ ├── AbstractBeanFactory.java

│ │ │ │ ├── BeanDefinitionReader.java

│ │ │ │ ├── BeanDefinitionRegistry.java

│ │ │ │ ├── CglibSubclassingInstantiationStrategy.java

│ │ │ │ ├── DefaultListableBeanFactory.java

│ │ │ │ ├── DefaultSingletonBeanRegistry.java

│ │ │ │ ├── InstantiationStrategy.java

│ │ │ │ └── SimpleInstantiationStrategy.java

│ │ │ ├── xml

│ │ │ │ └── XmlBeanDefinitionReader.java

│ │ │ ├── BeanFactory.java

│ │ │ ├── ConfigurableListableBeanFactory.java

│ │ │ ├── HierarchicalBeanFactory.java

│ │ │ └── ListableBeanFactory.java

│ │ ├── BeansException.java

│ │ ├── PropertyValue.java

│ │ └── PropertyValues.java

│ ├── core.io

│ │ ├── ClassPathResource.java

│ │ ├── DefaultResourceLoader.java

│ │ ├── FileSystemResource.java

│ │ ├── Resource.java

│ │ ├── ResourceLoader.java

│ │ └── UrlResource.java

│ └── utils

│ └── ClassUtils.java

└── test

└── java

└── cn.bugstack.springframework.test

├── bean

│ ├── UserDao.java

│ └── UserService.java

└── ApiTest.java

前面我都是没有放设计图的,但是这一部分比较繁琐,内容比较多,我觉得有必要看看了:

1.资源加载接口定义和实现

其实就是对三种资源获取方式的不同处理模式,可以看作一个处理节点:

public interface Resource {

InputStream getInputStream() throws IOException;

}

public class ClassPathResource implements Resource {

private final String path;

private ClassLoader classLoader;

public ClassPathResource(String path) {

this(path, (ClassLoader) null);

}

public ClassPathResource(String path, ClassLoader classLoader) {

Assert.notNull(path, "Path must not be null");

this.path = path;

this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());

}

@Override

public InputStream getInputStream() throws IOException {

InputStream is = classLoader.getResourceAsStream(path);

if (is == null) {

throw new FileNotFoundException(

this.path + " cannot be opened because it does not exist");

}

return is;

}

}

public class FileSystemResource implements Resource {

private final File file;

private final String path;

public FileSystemResource(File file) {

this.file = file;

this.path = file.getPath();

}

public FileSystemResource(String path) {

this.file = new File(path);

this.path = path;

}

@Override

public InputStream getInputStream() throws IOException {

return new FileInputStream(this.file);

}

public final String getPath() {

return this.path;

}

}

public class UrlResource implements Resource{

private final URL url;

public UrlResource(URL url) {

Assert.notNull(url,"URL must not be null");

this.url = url;

}

@Override

public InputStream getInputStream() throws IOException {

URLConnection con = this.url.openConnection();

try {

return con.getInputStream();

}

catch (IOException ex){

if (con instanceof HttpURLConnection){

((HttpURLConnection) con).disconnect();

}

throw ex;

}

}

}

2.资源工厂路由

这里实际上是叫资源装载器,但是我觉得这就是个工厂。

上述的URL、Classpath、File三种处理都可以用一个工厂来路由,因此我们选择新增 DefaultResourceLoader 作为节点工厂,通过不同的资源获取方式来生产一个标准的 Resource 。

public interface ResourceLoader {

/**

* Pseudo URL prefix for loading from the class path: "classpath:"

*/

String CLASSPATH_URL_PREFIX = "classpath:";

Resource getResource(String location);

}

public class DefaultResourceLoader implements ResourceLoader{

@Override

public Resource getResource(String location) {

Assert.notNull(location, "Location must not be null");

if (location.startsWith(CLASSPATH_URL_PREFIX)) {

return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()));

}

else {

try {

URL url = new URL(location);

return new UrlResource(url);

} catch (MalformedURLException e) {

return new FileSystemResource(location);

}

}

}

}

这里的工厂设计得比较有意思,其实从代码看下来,无论你传什么最后都不会报错,即使这个字符串既不是 URL ,也不是 File 或者 Classpath 。

那什么时候会报错呢?

其实是在下面这一步,如果乱填就会因为找不到资源而自动报错,当然,这里只展示了classpath的处理方式,其他两个处理节点其实也是有这样的报错处理的。

@Override

public InputStream getInputStream() throws IOException {

InputStream is = classLoader.getResourceAsStream(path);

if (is == null) {

throw new FileNotFoundException(

this.path + " cannot be opened because it does not exist");

}

return is;

}

3.Bean定义的读取

这是一条业务链:

BeanDefinitionReader ->AbstractBeanDefinitionReader -> XmlBeanDefinitionReader

而且还是很好理解的,但是需要注意一点,这里的抽象类不是作为流程骨架的,因此没有使用模板方法模式,这个抽象类是作为基础设施的提供者。

只有一个作用:提供 registry 和 resourceLoader 给子类直接使用。

这是接口:

public interface BeanDefinitionReader {

BeanDefinitionRegistry getRegistry();

ResourceLoader getResourceLoader();

void loadBeanDefinitions(Resource resource) throws BeansException;

void loadBeanDefinitions(Resource... resources) throws BeansException;

void loadBeanDefinitions(String location) throws BeansException;

}

public abstract class AbstractBeanDefinitionReader implements BeanDefinitionReader {

private final BeanDefinitionRegistry registry;

private ResourceLoader resourceLoader;

protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {

this(registry, new DefaultResourceLoader());

}

public AbstractBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) {

this.registry = registry;

this.resourceLoader = resourceLoader;

}

@Override

public BeanDefinitionRegistry getRegistry() {

return registry;

}

@Override

public ResourceLoader getResourceLoader() {

return resourceLoader;

}

}

子类专门用于解析XML文件,这个文件的来路我们不管,因为我们的资源工厂已经将这个资源包装为一个标准资源了(Resource),但是这个类最后只能解析XML资源。

如果不是合法XML资源,将直接在下面那一行代码报错:

但是注意:XmlBeanDefinitionReader 不关心资源文件名后缀,而是直接把 Resource 的输入流交给 XML 解析器。

XmlUtil.readXML(inputStream);

public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {

public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {

super(registry);

}

public XmlBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) {

super(registry, resourceLoader);

}

@Override

public void loadBeanDefinitions(Resource resource) throws BeansException {

try {

try (InputStream inputStream = resource.getInputStream()) {

doLoadBeanDefinitions(inputStream);

}

} catch (IOException | ClassNotFoundException e) {

throw new BeansException("IOException parsing XML document from " + resource, e);

}

}

@Override

public void loadBeanDefinitions(Resource... resources) throws BeansException {

for (Resource resource : resources) {

loadBeanDefinitions(resource); 拼多多帮助力入口

}

}

@Override

public void loadBeanDefinitions(String location) throws BeansException {

ResourceLoader resourceLoader = getResourceLoader();

Resource resource = resourceLoader.getResource(location);

loadBeanDefinitions(resource);

}

protected void doLoadBeanDefinitions(InputStream inputStream) throws ClassNotFoundException {

Document doc = XmlUtil.readXML(inputStream);

Element root = doc.getDocumentElement();

NodeList childNodes = root.getChildNodes();

for (int i = 0; i < childNodes.getLength(); i++) {

// 判断元素

if (!(childNodes.item(i) instanceof Element)) continue;

// 判断对象

if (!"bean".equals(childNodes.item(i).getNodeName())) continue;

// 解析标签

Element bean = (Element) childNodes.item(i);

String id = bean.getAttribute("id");

String name = bean.getAttribute("name");

String className = bean.getAttribute("class");

// 获取 Class,方便获取类中的名称

Class clazz = Class.forName(className);

// 优先级 id > name

String beanName = StrUtil.isNotEmpty(id) ? id : name;

if (StrUtil.isEmpty(beanName)) {

beanName = StrUtil.lowerFirst(clazz.getSimpleName());

}

// 定义Bean

BeanDefinition beanDefinition = new BeanDefinition(clazz);

// 读取属性并填充

for (int j = 0; j < bean.getChildNodes().getLength(); j++) {

if (!(bean.getChildNodes().item(j) instanceof Element)) continue;

if (!"property".equals(bean.getChildNodes().item(j).getNodeName())) continue;

// 解析标签:property

Element property = (Element) bean.getChildNodes().item(j);

String attrName = property.getAttribute("name");

String attrValue = property.getAttribute("value");

String attrRef = property.getAttribute("ref");

// 获取属性值:引入对象、值对象

Object value = StrUtil.isNotEmpty(attrRef) ? new BeanReference(attrRef) : attrValue;

// 创建属性信息

PropertyValue propertyValue = new PropertyValue(attrName, value);

beanDefinition.getPropertyValues().addPropertyValue(propertyValue);

}

if (getRegistry().containsBeanDefinition(beanName)) {

throw new BeansException("Duplicate beanName[" + beanName + "] is not allowed");

}

// 注册 BeanDefinition

getRegistry().registerBeanDefinition(beanName, beanDefinition);

}

}

}

4.测试

最后测试一下,事实上,这里的使用方法已经越来越接近Spring框架的正常使用了:

private DefaultResourceLoader resourceLoader;

@Before

public void init() {

resourceLoader = new DefaultResourceLoader();

}

@Test

public void test_xml() {

// 1.初始化 BeanFactory

DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

// 2. 读取配置文件&注册Bean

XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);

reader.loadBeanDefinitions("classpath:spring.xml");

// 3. 获取Bean对象调用方法

UserService userService = beanFactory.getBean("userService", UserService.class);

String result = userService.queryUserInfo();

System.out.println("测试结果:" + result);

}

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧