KZKY memo

自分用メモ.

beanファイルのbeanが継承関係にあるとき

parentでscope="singleton"のときのメモ
  • childのscope="singleton or prototype"でもparentのconstructorが2回呼ばれている.
    • beanファイルを読み込んだ時 (parentがつくられたとき)
    • beanファイルを読み込んだ時 (childがつくられたとき)
parentでscope="prototype"のとき
  • parentのconstructorが1回呼ばれている.
beanファイルでchildのみ定義してある時
  • parentのconstructorが当然1回呼ばれている.
parentでscope="singleton"のときのサンプル

beanサンプル

<?xml version="1.0" encoding="UTF-8"?>
<bean id="parent" scope="singleton" class="edu.kzk.spring_sample.extended_singleton.Parent">
<property name="var" value="parent"/>
</bean>

<bean id="child" scope="prototype" parent="parent" class="edu.kzk.spring_sample.extended_singleton.Child">
<property name="var" value="child"/>
</bean>
</beans>

output (抜粋)

--- before new ClassPathXmlApplicationContext
...
[20:38:21 INFO  Parent] - ### Constructor ###
[20:38:21 DEBUG AbstractAutowireCapableBeanFactory] - Eagerly caching bean 'parent' to allow for resolving potential circular references
[20:38:21 INFO  Parent] - ## setVar ##
[20:38:21 DEBUG AbstractAutowireCapableBeanFactory] - Finished creating instance of bean 'parent'
...
--- before getBean
[20:38:21 DEBUG AbstractAutowireCapableBeanFactory] - Creating instance of bean 'child'
[20:38:21 INFO  Parent] - ### Constructor ###
[20:38:21 INFO  Child] - ### Constructor ###
[20:38:21 INFO  Parent] - ## setVar ##
[20:38:21 DEBUG AbstractAutowireCapableBeanFactory] - Finished creating instance of bean 'child'
--- after getBean
...

parentでscope="singleton"のときは,parentが2回作られているのだろうか?
2回作られていると,singletonではないのでおかしくないか?
でも,ログを見る限りcreating instance of bean 'parent'は1回のみ呼び出されているので,constructorが呼び出されていてもparentの実態は1つ(new Parentは1回)なのだろう.

そもそもParentのデフォルトコンストラクタが呼ばれているだけで,new Parentしているわけではないか...