property和constructor-arg设值注入

本文介绍了Spring框架中依赖注入的两种主要方式:通过构造函数注入和通过set方法注入,并通过具体的XML配置示例和Java代码展示了如何实现这两种注入方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、注入的方式 

配置文件的根元素是beans,每个组件使用bean元素来定义,如果使用设值注入,可以利用以下方式,来指定组件的属性。

  constructor-arg:通过构造函数注入。 

  property:通过setxx方法注入。 

二、使用方法

(1)property的简单使用

spring的xml配置文件:

<bean id="baseInfo" class="com.learn.spring.baseInfo">
	<property name="name" value="sky"/>
	<property name="age" value="24"/>
</bean>

java文件:

package com.learn.spring;
public class baseInfo {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
(2)constructor-arg的简单使用

spring的xml配置文件:

<bean id="man" class="com.learn.spring.Man">
	<!-- 当构造函数有多个参数时,可以使用index属性,index属性的值从0开始 -->
	<constructor-arg value="zzy" index="0">
	</constructor-arg>

	<!-- 在使用构造子注入时,需要注意的问题是要避免构造子冲突的情况发生 
		如 man(String value) man(int value)构造函数冲突 
		使用type属性制定参数类型,明确的告诉需要使用哪个构造函数 -->
	<constructor-arg value="10" type="int" index="1">
	</constructor-arg>

	<constructor-arg>
		<list>
			<value>movie</value>
			<value>music</value>
		</list>
	</constructor-arg>

	<constructor-arg>
		<set>
			<value>Lady is GaGa</value>
			<value>GaGa is Lady</value>
		</set>
	</constructor-arg>

	<constructor-arg>
		<map>
			<entry key="zhangsan" value="male"></entry>
			<entry key="lisi" value="female"></entry>
		</map>
	</constructor-arg>

	<!-- 最后一个参数是boolean类型的参数,在配置的时候可以是true/false或者0/1 -->
	<constructor-arg index="5" value="0">
	</constructor-arg>

	<constructor-arg>
		<props>
			<prop key="name">sky</prop>
		</props>
	</constructor-arg>
</bean>

为了注入集合属性,Spring提供了list,map,set和props标签,分别对应List,Map,Set和Properties,我们甚至可以嵌套的使用它们(List of Maps of Sets of Lists)。

java文件:

public class Man {
	private String name;
	private int age;
	private List hobby;
	private Map friends;
	private Set set;
	private boolean ifMarried;    
	private Properties properties;
	public Man() {
	}
	public Man(String name, int age, List hobby, Map friends, Set set, boolean ifMarried, Properties properties) {  
        this.name = name;  
        this.age = age;  
        this.hobby = hobby;  
        this.friends = friends;  
        this.set = set;  
        this.ifMarried = ifMarried;  
    	this.properties = properties;
    }
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值