ホームページ  >  記事  >  Java  >  Spring コンテナーでの Bean の初期化に関する簡単な説明

Spring コンテナーでの Bean の初期化に関する簡単な説明

高洛峰
高洛峰オリジナル
2017-01-24 15:19:241217ブラウズ

Spring コンテナに Bean を追加するとき、そのスコープ属性が指定されていない場合、デフォルトはシングルトン、つまりシングルトンです。

たとえば、最初に 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 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>

を設定します。

実行後、p1 が表示されます。p2 で入力された内容は同じであり、Spring の Bean がシングルトン。

シングルトンBeanが不要な場合は、scope属性をprototypeに変更できます

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);
 }
  
}

このように、Springコンテナを通じて取得されたBeanはシングルトンではありません。

デフォルトでは、Spring コンテナは起動後にすべての Bean のオブジェクトを自動的に作成します。Bean を取得するときにオブジェクトを作成したい場合は、lazy-init 属性を使用できます。この属性には、defalut、true、および 3 つの値があります。そして偽り。デフォルトは false と同じです。true に指定すると、Bean オブジェクトは Bean を取得するまで作成されません。

Spring コンテナーでの Bean の初期化について簡単に説明した上記の記事は、編集者が共有したすべての内容です。参考にしていただければ幸いです。また、PHP 中国語 Web サイトをサポートしていただければ幸いです。

Spring コンテナーでの Bean の初期化に関連するその他の記事については、PHP 中国語 Web サイトに注目してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。