spring-ioc

来源:互联网 发布:知阅小说网_原创小说网 编辑:程序博客网 时间:2024/06/06 00:18

实例化bean的三种方式:

<!-- 默认的           把类添加到spring容器中            -->           <bean id="helloWorld" class="com.example.vic.test_spring.ioc_di_setter_HelloWorld.HelloWorld">            <!-- 静态工厂    工厂方法是静态的-->          <bean  id="helloWorld1" class="com.example.vic.test_spring.ioc_di_setter_HelloWorld.FactoryClassHelloWorld1" factory-method="getInstance">           </bean>             <!-- 实例工厂 -->           <bean id="factoryHelloWorld" class="com.example.vic.test_spring.ioc_di_setter_HelloWorld.FactoryClassHelloWorld2">           </bean>           <bean id="helloWorld2" factory-bean="factoryHelloWorld" factory-method="getInstance">           </bean>

注意

 <bean id="helloWorld" class="com.example.vic.test_spring.ioc_di_setter_HelloWorld.HelloWorld" lazy-init="true" scope="prototype" init-method="">            <!--注入属性-->    <property name="" value=""></property>  </bean> 

第一点– 因为ApplicationContext context =
new ClassPathXmlApplicationContext(“applicationContext.xml”);
会加载所有中的类并生成id类的对象。

第二点 lazy-init=”default” 是默认false,不是延迟加载(加载xml同时生成对象), lazy-init=”true” ,会延迟加载,不会加载xml同时生成对象。

第三点–还有个属性scope=“prototype” 他会创造多个bean对象,因为spring容器默认为单类模式,只会创造一个对象。

第四点–执行顺序,
0.启动spring容器
1.创建helloWorld对象
2.setter 方法注入
3.init-method
4. destroy-method 注销时

public class HelloWorld {    public HelloWorld() {        System.out.println("new instance");    }    public void printHelloWorld(){        System.out.println("调用方法");    }}
public class FactoryClassHelloWorld1 {    //工厂类静态方法    public static HelloWorld getInstance(){        return new HelloWorld();    }}
public class FactoryClassHelloWorld2 {    //工厂类方法    public  HelloWorld getInstance(){        return new HelloWorld();    }}
public class Test_mothed {    /**     * spring容器在默认的情况下使用默认的构造函数创建对象(默认构造函数可写可不写)     */    @Test    public void testMothed(){        ApplicationContext context =             new ClassPathXmlApplicationContext("applicationContext.xml");    HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");    helloWorld.printHelloWorld();    }    /*     *  在spring容器 内部,调用了HelloWorldFactory中的getInstance静态方法     * 而该方法的内容就是创建对象的过程,是由程序员来完成     * */    @Test    public void testFactory1(){        ApplicationContext context =             new ClassPathXmlApplicationContext("applicationContext.xml");        HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld1");        helloWorld.printHelloWorld();    }    /**     * 实例工厂     *   1、spring容器创建一个实例工厂bean     *   2、该bean调用了工厂方法getInstance产生对象     */    @Test    public void testFactory2(){        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld2");        helloWorld.printHelloWorld();    }}
0 0
原创粉丝点击