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>
    

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

  • 相关阅读:
    Linux内核中的信号机制--一个简单的例子【转】
    国际C语言混乱代码大赛代码赏析(一)【转】
    宏内核与微内核【转】
    Linux内核USB驱动【转】
    USB驱动开发大全【转】
    Linux驱动程序学习【转】
    GPIO口及中断API函数【转】
    Linux的fasync驱动异步通知详解【转】
    request_irq() | 注册中断服务函数【转】
    混杂设备动态次设备号分析【转】
  • 原文地址:https://www.cnblogs.com/youcoding/p/12775385.html
Copyright © 2011-2022 走看看