Spring 内部Bean

1. 案例环境

1
2
3
4
5
@Data
public class Car {
private String name;
private Double price;
}
1
2
3
4
5
@Data
public class Person {
private Car car;
private Object[] arr;
}

2. 内部Bean不可获取

内部Bean不可获取,只供内部使用,外部不能获取。因此内部Bean设置id是没有意义的,相当于没有设置

2.1. 测试从容器中取出内部Bean

1
2
3
4
5
6
7
8
<bean id="person" class="bean.Person">
<property name="car">
<bean id="carInner" class="bean.Car">
<property name="name" value="carInner" />
<property name="price" value="5000.0" />
</bean>
</property>
</bean>
1
2
3
4
5
6
@Test
public void testIoc() throws Exception {
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = (Car) ioc.getBean("carInner");
System.out.println(car);
}

运行,抛出异常。虽然定义了内部Bean,并设置了ID,但是根据ID获取内部Bean时,还是提示Bean没有定义(注册)过,因此可知内部Bean是无法获取的

1
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'carInner' available

2.2. 测试使用ref引用内部Bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<bean id="person" class="bean.Person">
<property name="car">
<bean id="carInner" class="bean.Car">
<property name="name" value="carInner" />
<property name="price" value="5000.0" />
</bean>
</property>
<property name="arr">
<array>
<!-- ref引用内部Bean -->
<ref bean="carInner"/>
</array>
</property>
</bean>
1
2
3
4
5
6
@Test
public void testIoc() throws Exception {
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = ioc.getBean(Person.class);
System.out.println(person);
}

运行,也是提示Bean没有定义

1
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'carInner' while setting bean property 'arr' with key [0]; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'carInner' available

panchaoxin wechat
关注我的公众号
支持一下