首先写一个实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String lastName;
private int age;
private String gender;
}
其次在spring.xml中配置两个Person对象,person01和person02
<bean id="person01" class="com.hh.pojo.Person">
<property name="lastName" value="张三"/>
<property name="gender" value="男"/>
<property name="age" value="12"/>
</bean>
1.根据bean的id从IOC容器中获取bean对象
写一个测试类,根据bean的id获取bean的实例
public class MyTest {
public class MyTest {
//根据spring的配置文件得到ioc容器对象
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
@Test
public void test(){
Person person = (Person)context.getBean("person01");
System.out.println(person);
}
@Test
public void test2(){
Person person = (Person)context.getBean("person02");
System.out.println(person);
}
}
2.根据bean的class类型从IOC容器中获取bean对象
现在spring.xml中只注册了一个bean对象
<bean id="person01" class="com.hh.pojo.Person">
<property name="lastName" value="张三"/>
<property name="gender" value="男"/>
<property name="age" value="12"/>
</bean>
测试根据bean的类型从IOC容器中获取bean对象
public class MyTest2 {
//根据spring的配置文件得到ioc容器对象
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
@Test
public void test2(){
Person person = context.getBean(Person.class);
System.out.println(person);
}
}
这样获取bean对象有一个好处就是不用返回值类型不用强制转换
那么问来了,如果spring.xml中注册了两个bean对象呢?
<bean id="person01" class="com.hh.pojo.Person">
<property name="lastName" value="张三"/>
<property name="gender" value="男"/>
<property name="age" value="12"/>
</bean>
<bean id="person02" class="com.hh.pojo.Person">
<property name="lastName" value="李四"/>
</bean>
此时按照bean的类型来找时,就会报错
遇到这种情况,我们只能通过bean的id来获取bean对象,那么我们又不想类型强转怎么办??
public class MyTest2 {
//根据spring的配置文件得到ioc容器对象
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
@Test
public void test(){
Person person = context.getBean("person01",Person.class);
System.out.println(person);
}
@Test
public void test2(){
Person person = context.getBean(Person.class);
System.out.println(person);
}
}