实习笔记 —— IOC反转控制(xml配置文件 + 注解)

系列文章目录

实习笔记 —— Spring基础



一、使用xml配置文件实现属性注入

学了好多中属性注入的方式,记录在/spring01/src/applicationContext.xml中,这里只记录常用的 setter 方法注入。

1.setter方法注入

①当属性类型为标量(标准变量)时:

property 标签使用的是 value 属性

a.实体类:

package com.high.demo2;

public class Car2 {
   
	private String cName;
	private double price;
	
	public String getcName() {
   
		return cName;
	}
	public void setcName(String cName) {
   
		this.cName = cName;
	}
	public double getPrice() {
   
		return price;
	}
	public void setPrice(double price) {
   
		this.price = price;
	}
	@Override
	public String toString() {
   
		return "Car2 [cName=" + cName + ", price=" + price + "]";
	}
	
	
}

b.xml配置文件写法:

<bean id="car2" class="com.high.demo2.Car2">
   		<!-- 当属性类型为标量时,使用value;当属性类型为引用类型时,使用ref -->
   		<property name="cName" value="SScar"></property>
   		<property name="price" value="999999"></property>
</bean>

c.测试类:

package com.high.demo2;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDemo2 {
   
	// 2.1 setter方法属性注入(创建DI)测试  —— 注入标量属性
	@Test 
	public void setDemo() {
   
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		Car2 car2 = (Car2)applicationContext.getBean("car2");
		
		System.out.println(car2);
	}
}

d.测试结果:
在这里插入图片描述

②属性类型为引用类型时:

property 标签使用的是 ref 属性

a.实体类:

package com.high.demo2;

public class Employee {
   
	private String uName;
	private Car car;
	
	public String getuName() {
   
		return uName;
	}
	public void setuName(String uName) {
   
		this.uName = uName;
	}
	public Car getCar() {
   
		return car;
	}
	public void setCar(Car car) {
   
		this.car = car;
	}
	
	@Override
	public String toString() {
   
		return "Employee [uName=" + uName + ", car=" + car + "]";
	}
}

b.配置文件:

<!-- 1.构造方法注入属性 -->
   	<bean id="car" class="com.high.demo2.Car">
   		<constructor-arg name="cName" value="ABC"></constructor-arg>
   		<constructor-arg name="price" value="10000"></constructor-arg>
   	</bean>

<!-- ref属性调用已经生成的类,ref对应其他类的id或name -->
   	<bean id="employee" class
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值