依赖项构造方法注入示例
我们可以通过构造函数注入依赖项。 <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空
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析