Spring的属性注入(案例+解析)

// 创建工程

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“applicationContext.xml”);

// 获得到对应XML当中的对象

Car car = (Car) applicationContext.getBean(“car”);

System.out.println(car);

}

}

在这里插入图片描述

2、Set方法的方式的属性注入
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

package com.itzheng.spring.demo4;

/*

  • set方法的属性注入

*/

public class Car2 {

private String name;

private Double price;

public void setName(String name) {

this.name = name;

}

public void setPrice(Double price) {

this.price = price;

}

@Override

public String toString() {

return “Car2 [name=” + name + “, price=” + price + “]”;

}

}

/*

set方法注入

*/

@Test

public void demo2() {

// 创建工程

ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“applicationContext.xml”);

// 获得到对应XML当中的对象

Car2 car2 = (Car2) applicationContext.getBean(“car2”);

System.out.println(car2);

}

在这里插入图片描述

二、对象类型注入


1、set方法来注入对象

创建类和对应的set方法

package com.itzheng.spring.demo4;

public class Employee {

private String name;

private Car2 car2;

public void setName(String name) {

this.name = name;

}

public void setCar2(Car2 car2) {

this.car2 = car2;

}

@Override

public String toString() {

return “Employee [name=” + name + “, car2=” + car2 + “]”;

}

}

设置XML属性配置

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

value是用来设置普通类型的值。

ref是用来设置其他类的id 或者name ref是另外一个普通类型

在这里插入图片描述

在这里插入图片描述

2、构造方法来注入对象

创建类和对应的构造方法

package com.itzheng.spring.demo4;

public class Boos {

private String name;

private Car car;

public Boos(String name, Car car) {

super();

this.name = name;

this.car = car;

}

@Override

public String toString() {

return “Boos [name=” + name + “, car=” + car + “]”;

}

}

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns=“http://www.springframework.org/schema/beans”

xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

最后

给大家送一个小福利

附高清脑图,高清知识点讲解教程,以及一些面试真题及答案解析。送给需要的提升技术、准备面试跳槽、自身职业规划迷茫的朋友们。

n>

最后

给大家送一个小福利

[外链图片转存中…(img-6fe0tX4Q-1721158175952)]

附高清脑图,高清知识点讲解教程,以及一些面试真题及答案解析。送给需要的提升技术、准备面试跳槽、自身职业规划迷茫的朋友们。

[外链图片转存中…(img-5h0fWlPW-1721158175953)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值