IOC容器实例化对象的三种方式

124 阅读1分钟

1.默认的方式:构造器实例化

    <bean id="userService" class="com.zks.Service.UserService">
    </bean>
        //获取spring的上下文环境
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
        //通过id属性值获取指定的bean对象
        UserService userService= (UserService) applicationContext.getBean("userService");
        //调用实例化好的javaBean对象的方法
        userService.test();

2.静态工厂实例化
第一步:先准备bean对象

public class TypeService {
    public void test(){
        System.out.println("TypeService.test");
    }
}

第二步:需要先建议一个工厂包,然后再在里面建一个静态工厂类,类中写静态方法


/**
 * 静态工厂类
 */
public class StaticFactory {
    /**
     * 定义对应的静态方法
     * @return
     */
    public static TypeService createService(){
        return new TypeService();
    }
}

第三步:写配置文件
在这里插入图片描述

<!--    静态工厂-->
    <bean id="typeService" class="com.zks.factory.StaticFactory" factory-method="createService">
    </bean>

第四步:测试

 //获取spring的上下文环境
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
        TypeService typeService= (TypeService) applicationContext.getBean("typeService");
        typeService.test();

两者的区别是:用默认构造器创建对象是在IOC容器里就创建好了,而用静态工厂,只有去调用creatService这个静态方法的时候才会去实例化对象,你可以在这之前加点你想加的东西

第三种方法:实例化工厂方法
第一步:准备Bean对象

public class TypeController {
    public void test(){
        System.out.println("TypeController.test");
    }
}

第二步:需要先建议一个工厂包,然后再在里面建一个工厂类,类中写方法

/**
 * 实例化工厂
 */
public class InstanceFactory {
    /**
     * 定义实例化方法
     * @return
     */
    public TypeController createTypeController(){
        return new TypeController();
    }
}

第三步:写配置文件

在这里插入图片描述

<!--   实例化工厂 -->
<!--    工厂对象-->
    <bean id="instanceFactory" class="com.zks.factory.InstanceFactory"></bean>
<!--    bean对象-->
    <bean id="typeController" factory-bean="instanceFactory" factory-method="createTypeController"></bean>

第四步:测试

 //获取spring的上下文环境
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
        TypeController typeController= (TypeController) applicationContext.getBean("typeController");
        typeController.test();

在这里插入图片描述