思考:
- 使用Spring框架对象是谁创建的?
对象是由Spring容器创建的 - 使用Spring框架对象的属性是怎么设置的?
对象的属性是由Spring容器设置的
什么是控制反转(IOC)?
控制 : 谁来控制对象的创建 , 传统应用程序的对象是由程序本身控制创建的 , 使用Spring框架后 , 对象是由Spring来创建的。
反转 : 程序本身不创建对象 , 而变成被动的接收对象
IOC是一种编程思想,由主动的编程变成被动的接收
创建bean的三种方式
- 使用默认构造方法创建
在spring配置文件中使用bean标签,配以id和class(全类名)属性之后,且没有其他属性和标签时采用的就是默认的构造函数创建对象,此时若类中没有默认构造函数,则对象无法创建
在Spring核心配置文件beans.xml文件中配置
<bean id="person" class="com.entity.Person"></bean>
测试:
@Test
public void test(){
//通过ClassPathXmlApplicationContext对象加载配置文件方式将javabean对象交给spring来管理
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//获取Spring容器中的bean对象,通过id和类字节码来获取
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person);
}
结果:
- 使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入Spring容器中)
通过Human类创建Person类对象
public class Human {
public Human(){
System.out.println("human对象被创建出来了");
}
//创建person对象方法
public Person getPerson(){
System.out.println("获取person对象");
return new Person();
}
}
在Spring核心配置文件beans.xml文件中配置
<!-- 先创建出某个类对象交给Spring来管理-->
<bean id="human" class="com.entity.Human"></bean>
<!--通过当前类中的方法创建需要的对象并存入Spring容器中-->
<bean id="person" factory-bean="human" factory-method="getPerson"></bean>
测试:
@Test
public void test(){
//通过ClassPathXmlApplicationContext对象加载配置文件方式将javabean对象交给spring来管理
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//获取Spring容器中的bean对象,通过id和类字节码来获取
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person);
}
结果:
- 使用工厂中的静态方法创建对象(使用某个类中的静态方法创建方法,并存入spring容器)
通过某个类中静态方法创建对象
public class StaticHuman {
//通过静态方法创建对象
public static Person getPerson(){
System.out.println("获取person对象");
return new Person();
}
}
测试类:
@Test
public void test(){
//通过ClassPathXmlApplicationContext对象加载配置文件方式将javabean对象交给spring来管理
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
//获取Spring容器中的bean对象,通过id和类字节码来获取
Person person = applicationContext.getBean("person", Person.class);
System.out.println(person);
}
结果: