欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

浅谈spring容器中bean的初始化

时间:2021-06-04 07:54:45|栏目:JAVA代码|点击:

当我们在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时才创建对象。

上一篇:基于SpringBoot bootstrap.yml配置未生效的解决

栏    目:JAVA代码

下一篇:SpringBoot实现钉钉机器人消息推送的示例代码

本文标题:浅谈spring容器中bean的初始化

本文地址:http://www.codeinn.net/misctech/135185.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有