Q:當一個單例bean依賴了一個延遲初始化bean的時候,這個延遲初始化bean會在什麼時候被初始化?
A:在Spring容器啓動的時候。
解釋:默認情況下單例bean會在Spring容器啓動時立即被初始化。
Q:自動注入有哪幾種方式?構造器自動注入模式按哪種方式匹配?自動注入有什麼限制和缺點?
A:自動注入的方式有No(Default)、byName、byType、constructor;構造器自動注入模式按類型(type)匹配。
自動注入的限制和缺點:
1.會被顯式指定的注入覆蓋,不能自動注入簡單類型及簡單類型數組。
2.沒有顯式注入精確。
3.文檔生成工具可能無法使用注入的信息。
4.多個bean 可能會匹配到同一個type,如果只需要單一的值,將會拋出異常。
Q:Spring有哪幾種注入方式?什麼情況下會用到方法注入?
A:Spring注入方式有setter注入、構造器注入、方法注入。
當一個單例bean的方法調用依賴一個prototype bean,而每次調用需要一個新的prototype bean的時 候,可以使用方法注入。因爲單例bean一旦被創建,狀態將不可改變,而每次調用它的方法時又需要一個新的prototype bean,這時候可以通過方法注入每次獲取一個新的prototype bean。
方法注入有三種方式:
1.lookup-method。(推薦)
2.通過實現ApplicationContextAware,但是不推薦,因爲這樣做耦合了Spring的API。不符合低耦合的設計原則。
3.手工方法替換。需實現MethodReplacer接口。
Q:Spring bean的生命週期有哪幾種?
A:Singleton(默認)、prototype、request(HttpRequest)、session(HttpSession)、global session。
Q:如何注入一個範圍bean(例如HttpRequest)?
A:在範圍bean裏面注入一個AOP代理
<!-- an HTTP Session-scoped bean exposed as a proxy --> <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"> <!-- instructs the container to proxy the surrounding bean --> <aop:scoped-proxy/> </bean> <!-- a singleton-scoped bean injected with a proxy to the above bean --> <bean id="userService" class="com.foo.SimpleUserService"> <!-- a reference to the proxied userPreferences bean --> <property name="userPreferences" ref="userPreferences"/> </bean>
Q:如果一個bean配置了多個初始化機制,會發生什麼?
A:將按照下面的順序調用初始化方法:
1.標有@PostConstruct的方法
2.afterPropertiesSet()方法of InitializingBean
3.自定義的init()方法
注:銷燬順序於此類似
Q:Spring裏的bean可以繼承嗎?Spring裏bean的繼承和java的繼承有什麼區別?
A:Java的類繼承不能繼承私有成員變量,Spring的可以。在Spring的bean繼承中,父類裏有的變量子類裏也要有。
Q: