zoukankan      html  css  js  c++  java
  • Spring 由构造函数自动装配

    Spring 由构造函数自动装配,这种模式与 byType 非常相似,但它应用于构造器参数。

    Spring 容器看作 beans,在 XML 配置文件中 beans 的 autowire 属性设置为 constructor。然后,它尝试把它的构造函数的参数与配置文件中 beans 名称中的一个进行匹配和连线。如果找到匹配项,它会注入这些 bean,否则,它会抛出异常。

    例如,在配置文件中,如果一个 bean 定义设置为通过构造函数自动装配,而且它有一个带有 SpellChecker 类型的参数之一的构造函数,那么 Spring 就会查找定义名为 SpellChecker 的 bean,并用它来设置构造函数的参数。你仍然可以使用 标签连接其余属性。

    其他与上个示例相同,但TextEditor.java 文件需要增加一个构造函数:

    package hello;
    
    public class TextEditor {
        private SpellChecker spellChecker;
        private String name;
        // 构造函数
        public TextEditor(SpellChecker spellChecker, String name){
            this.spellChecker = spellChecker;
            this.name = name;
        }
        // a setter method to inject the dependency.
        public void setSpellChecker(SpellChecker spellChecker){
            System.out.println("Inside setSpellChecker.");
            this.spellChecker = spellChecker;
        }
        // a getter method to return spellChecker
        public SpellChecker getSpellChecker(){
            return spellChecker;
        }
        public void setName(String name){
            this.name = name;
        }
        public String getName(){
            return name;
        }
    
        public void spellCheck(){
            spellChecker.checkSpelling();
        }
    }
    

    使用自动装配 “by constructor”,那么 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: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 https://www.springframework.org/schema/util/spring-util.xsd">
    
        <!-- Definition for textEditor bean-->
        <bean id="textEditor" class="hello.TextEditor" autowire="constructor">
            <constructor-arg value="Generic Text Editor"/>
        </bean>
    
        <!-- Definition for spellChecker bean -->
        <bean id="SpellChecker" class="hello.SpellChecker">
        </bean>
    
    </beans>
    

    每天学习一点点,每天进步一点点。

  • 相关阅读:
    「酷客多」关注:马化腾公开演讲,透露2017年春节前会推出“小程序”
    微信小程序购物商城系统开发系列-目录结构
    微信小程序购物商城系统开发系列-工具篇
    上海闪酷成为京东商城第一批独立软件开发商(ISV)
    【FFMPEG】关于硬解码和软解码
    Git 别名配置
    【Linux】扩展阿里云数据盘分区和文件系统
    Python实现MQTT接收订阅数据
    【Linux】Devops的一些运维工具
    【Linux】YUM Repositories for CentOS, RHEL & Fedora Systems
  • 原文地址:https://www.cnblogs.com/youcoding/p/12775385.html
Copyright © 2011-2022 走看看