Spring教程

依赖项构造方法注入示例

我们可以通过构造函数注入依赖项。 <bean><constructor-arg>子元素用于构造函数注入。在这里,我们要注入
原始和基于字符串的值 从属对象(包含对象) 集合值等

注入原始值和基于字符串的值

让我们看一下注入原始值和基于字符串的简单示例价值观。我们在这里创建了三个文件:
Employee.java applicationContext.xml Test.java
Employee.java
这是一个简单的类,包含两个字段id和name。此类中有四个构造函数和一个方法。
package com.lidihuo;
public class Employee {
private int id;
private String name;
public Employee() {System.out.println("def cons");}
public Employee(int id) {this.id = id;}
public Employee(String name) { this.name = name;}
public Employee(int id, String name) {
    this.id = id;
    this.name = name;
}
void show(){
    System.out.println(id+" "+name);
}
}
applicationContext.xml
我们通过此文件将信息提供给Bean。 constructor-arg元素调用构造函数。在这种情况下,将调用int类型的参数化构造函数。 Constructor-arg元素的value属性将分配指定的值。 type属性指定将调用int参数构造函数。
<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e" class="com.lidihuo.Employee">
<constructor-arg value="10" type="int"></constructor-arg>
</bean>
</beans>
Test.java
此类从applicationContext.xml文件获取Bean并调用show方法。
package com.lidihuo;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
    public static void main(String[] args) {
        
        Resource r=new ClassPathResource("applicationContext.xml");
        BeanFactory factory=new XmlBeanFactory(r);
        
        Employee s=(Employee)factory.getBean("e");
        s.show();
        
    }
}
输出: 10空

注入基于字符串的值

如果您未在构造函数arg元素中指定type属性,则默认情况下将调用字符串类型构造函数。
....
<bean id="e" class="com.lidihuo.Employee">
<constructor-arg value="10"></constructor-arg>
</bean>
....
如果如上所述更改bean元素,则将调用字符串参数构造函数,并且输出将为0 10。
输出: 0 10

您还可以按如下所示传递字符串文字:
....
<bean id="e" class="com.lidihuo.Employee">
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
....
输出: 0 Sonoo

您可以按以下方式传递整数文字和字符串
....
<bean id="e" class="com.lidihuo.Employee">
<constructor-arg value="10" type="int" ></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
....
输出: 10 Sonoo
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4