您的位置:首页技术文章
文章详情页

Spring容器初始化及问题解决方案

【字号: 日期:2023-09-02 09:34:37浏览:4作者:猪猪

1.Spring bean组件 ”默认为单例模式scope=“singleton, 运行JavaApplication容器启动时自动创建对象

scope=“prototype”为多例模式,请求条件下才创建对象

2beans组件 里面default-init-method初始化方法加载,范围比较大,当没有此方法时不会报错,default-destroy-method销毁方法,default-lazy-init=“true/false” 对象延时实例化

3.bean组件里面init-method初始化无此方法,会报错, destroy-method销毁方法,lazy-init=“true/false” 延时实例化

注意:

1.销毁方法对scope=“prototype”多例模式无效

2.AbstractApplicationContext可以关闭容器,可以调用close()方法,关闭容器,调用销毁方法

3.对象延时实例化对多例模式没有意义。

XML

<?xml version='1.0' encoding='UTF-8'?><beans xmlns='http://www.springframework.org/schema/beans' xmlns:context='http://www.springframework.org/schema/context' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:aop='http://www.springframework.org/schema/aop' xmlns:tx='http://www.springframework.org/schema/tx' xmlns:p='http://www.springframework.org/schema/p' xmlns:util='http://www.springframework.org/schema/util' xmlns:jdbc='http://www.springframework.org/schema/jdbc' xmlns:cache='http://www.springframework.org/schema/cache' xsi:schemaLocation=' http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd' default-init-method='initEmp' default-destroy-method='destroyEmp' default-lazy-init='true'> <bean init-method='initEmp' destroy-method='destroyEmp' lazy-init='false' scope='singleton' ></bean> </beans>

Test方法

//bean组件的默认方式 @Test public void beanInitTest() { AbstractApplicationContext appContext=new ClassPathXmlApplicationContext('com/tracy/xml/bean-init-destroy.xml'); ApplicationContext app=new ClassPathXmlApplicationContext('com/tracy/xml/bean-init-destroy.xml'); Emp emp=app.getBean('emp',Emp.class); System.out.print(emp); appContext.close(); }

通过构造完成初始bean属性,可以通过初始化完成

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: Spring
相关文章: