Spring IOC创建对象的三种方法
IoC又叫控制反转(Inversion of Control) 就是把对象交给Spring来创建
下面说一下创建对象的三种方式:
先创建一个实体类
package com.pojo;
public class Student{
public Student(){
System.out.println("调用了student的无参构造。。");
}
public void introduce(){
System.out.println("我是一名学生。。");
}
}
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">
<!--调用构造方法创建对象-->
<!--<bean class="com.pojo.Student" id="student">
</bean>-->
<!--用静态工厂创建对象-->
<bean class="com.factory.StaticFactory" id="stufactory" factory-method="studentFactory">
</bean>
<!--用实例工厂创建对象-->
<!--<bean class="com.factory.Factory" id="factory"></bean>
<bean id="stu" factory-bean="factory" factory-method="stuFactory"></bean>-->
</beans>
测试类的代码:
package com.test;
import com.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
public static void main(String[] args) {
//ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 无参构造
// Student student = context.getBean("student", Student.class);
// student.introduce();
//静态工厂
// Student stufactory = (Student) context.getBean("stufactory");
// stufactory.introduce();
// 实例工厂
// Student student = (Student) context.getBean("stu");
// student.introduce();
// 反射
// try {
// Student stu = (Student)(Class.forName("com.pojo.Student").newInstance());
// stu.introduce();
// } catch (Exception e) {
// e.printStackTrace();
// }
}
}