Spring实例化bean三种方式_静态工厂法

第一步:实体Bean2

package it.heima.Dao;

public class Bean2 {

}

第二步:实体Bean2Factory

package it.heima.Dao;

public class Bean2Factory {
    public static Bean2 initBean2(){
        return new Bean2();
    }
}

第三步:配置

<?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">

    <!--配置静态工厂的IOC-->
    <bean id="bean2" class="it.heima.Dao.Bean2Factory" factory-method="initBean2">
    </bean>
</beans>

第四步:测试

@Test
public void testBean2(){
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    Bean2 bean2 = applicationContext.getBean("bean2", Bean2.class);
    System.out.println(bean2);
}

猜你喜欢

转载自blog.csdn.net/weixin_42333583/article/details/81533555