关键词
spring Java eclipse bean 多例模式 prototype 懒加载 lazy-init
写在后面
- 性能简述:对于多例模式的懒加载配置是否失效的测试。
- 刚接触,摸索中,低级谬误,只是做个记录,轻喷。
(有谬误)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 id="myFactoryPrototypeExample" class="instance.BeanInstanceFactory"
scope="prototype" lazy-init="false"/>
<bean id="instanceFactoryInstancePrototypeExample" factory-bean="myFactoryPrototypeExample"
scope="prototype" lazy-init="false"/>
</beans>
运行的测试代码
package test;
import java.util.Calendar;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import instance.BeanClass;
import instance.Person;
import instance.User;
public class TestInstance {
// 对于多例模式,默认懒加载,即使设置 lazy-init="false" 也有效
@Test
public void test06(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("获取对象前");
// 参数是 xml 中待创立的对象的 id
BeanClass bc3 = (BeanClass)context.getBean("instanceFactoryInstancePrototypeExample");
System.out.println(bc3+bc3.message);
}
}
解决
- 思路:查看 xml 配置文件
- 起因:xml 配置文件有误。
- 解决:最初一个 bean 标签少写了 factory-method 属性。
(正确的)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 id="myFactoryPrototypeExample" class="instance.BeanInstanceFactory"
scope="prototype" lazy-init="false"/>
<!-- 上面这里少写了 factory-method-->
<bean id="instanceFactoryInstancePrototypeExample" factory-bean="myFactoryPrototypeExample"
factory-method="createBeanClassInstance" scope="prototype" lazy-init="false"/>
</beans>
包构造
(补充)BeanInstanceFactory 类
package instance;
public class BeanInstanceFactory {public BeanInstanceFactory(){System.out.println("我是一个实例工厂");
}
public BeanClass createBeanClassInstance(){return new BeanClass("调用实例工厂办法实例化 Bean");
}
}
(补充)BeanClass 类
package instance;
public class BeanClass {
public String message;
public BeanClass() {this.message = "构造方法实例化 Bean";}
public BeanClass(String message) {this.message = message;}
}
运行后果
参考
org.springframework.beans.factory.BeanCreationException:No bean class specified on bean definition