spring 引用其他bean

applicationContext.xml配置文件为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- 配置bean -->

<bean id="car" class="com.spring.Car">
<constructor-arg value="green"></constructor-arg>
<constructor-arg value="22"></constructor-arg>
</bean>


<bean id="person" class="com.spring.Person">
<property name="name" value="xiao"></property>
<property name="age" value="22"></property>
<property name="car" ref="car"></property>
</bean>
</beans>


package com.spring;


public class Car {
 private String name;
 private String color;
 private int num;
public Car(String color, int num) {
super();
this.color = color;
this.num = num;
}
@Override
public String toString() {
return "Car [name=" + name + ", color=" + color + ", num=" + num + "]";
}


}


package com.spring;


public class Person {
 private String name;
 private  int age;
 private Car car;
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;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";
}
 


}


测试类:

package com.spring;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Test {
public static void main(String[] args) {


//1.创建spring IOC容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");



Car car = (Car) ctx.getBean("car");
//System.out.println(car.toString());

Person person = (Person) ctx.getBean("person");
System.out.println(person);
}
}

运行结果为:

Person [name=xiao, age=22, car=Car [name=null, color=green, num=22]]




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值