依赖项构造方法注入示例

我们可以通过构造函数注入依赖项。 <bean>的 <constructor-arg>子元素用于构造函数注入。在这里,我们要注入

原始和基于字符串的值从属对象(包含对象)集合值等

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

让我们看一下注入原始值和基于字符串的简单示例价值观。我们在这里创建了三个文件:

Employee.java

Employee.java

这是一个简单的类,包含两个字段id和name。此类中有四个构造函数和一个方法。

package com.nhooo;
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);
}
}

 

注入基于字符串的值

如果您未在构造函数arg元素中指定type属性,则默认情况下将调用字符串类型构造函数。

....
<bean id="e" class="com.nhooo.Employee">
<constructor-arg value="10"></constructor-arg>
</bean>
....

如果如上所述更改bean元素,则将调用字符串参数构造函数,并且输出将为0 10。

输出: 0 10

您还可以按如下所示传递字符串文字:

....
<bean id="e" class="com.nhooo.Employee">
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
....

输出: 0 Sonoo

您可以按以下方式传递整数文字和字符串

....
<bean id="e" class="com.nhooo.Employee">
<constructor-arg value="10" type="int" ></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
....

输出: 10 Sonoo

applicationContext.xml

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.nhooo.Employee">
<constructor-arg value="10" type="int"></constructor-arg>
</bean>
</beans>

 

Test.java

Test.java

此类从applicationContext.xml文件获取Bean并调用show方法。

package com.nhooo;
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空



 

posted @   cnetsa  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示