当前位置: 移动技术网 > IT编程>开发语言>Java > 浅谈spring容器中bean的初始化

浅谈spring容器中bean的初始化

2019年07月22日  | 移动技术网IT编程  | 我要评论

当我们在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的初始化就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网