浅谈spring容器中bean的初始化
当我们在spring容器中添加一个bean时,如果没有指明它的scope属性,则默认是singleton,也就是单例的。
例如先声明一个bean:
public class People { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
在applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd"> <bean id="people" class="People" ></bean> </beans>
然后通过spring容器来获取它:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); People p1=(People) context.getBean("people"); People p2=(People) context.getBean("people"); System.out.println(p1); System.out.println(p2); } }
运行之后可以看出p1和p2输入的内容是一样的,说明spring中的bean是单例的。
如果不想要单例的bean,可以将scope的属性改为prototype
<bean id="people" class="People" scope="prototype" ></bean>
这样通过spring容器获取的bean就不是单例的了。
spring容器默认情况下在启动之后就自动为所有bean创建对象,若想要在我们获取bean时才创建的话,可以使用lazy-init属性
该属性有三个值defalut,true,false。默认是default,该值和false一样,都是spring容器启动时就创建bean对象,当指定为true时,
在我们获取bean时才创建对象。
以上这篇浅谈spring容器中bean的初始化就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
详解Spring中Bean后置处理器(BeanPostProcessor)的使用
BeanPostProcessor 接口也被称为Bean后置处理器,通过该接口可以自定义调用初始化前后执行的操作方法。本文将详细讲讲它的使用,需要的可以参考一下2022-06-06详解springboot+atomikos+druid 数据库连接失效分析
本文主要介绍了springboot+atomikos+druid 数据库连接失效分析,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2022-02-02Java中的HttpServletRequestWrapper用法解析
这篇文章主要介绍了Java中的HttpServletRequestWrapper用法解析,HttpServletRequest 对参数值的获取实际调的是org.apache.catalina.connector.Request,没有提供对应的set方法修改属性,所以不能对前端传来的参数进行修改,需要的朋友可以参考下2024-01-01
最新评论