Spring问题总结

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:

猜你喜欢

转载自wjkvipgood.iteye.com/blog/2030374