// 创建工程
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)]