Spring IOC创建对象的三种方法

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();
//        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值