Spring bean scope and life cycle
Spring Framework supports five scopes (three of which can only be used in web-based)。
One bean definition corresponds to one object instance in each Spring IoC container. |
|
A bean definition corresponds to multiple object instances. |
|
In an HTTP request, a bean definition corresponds to an instance; that is, each HTTP request will have its own bean instance, which is created according to a bean definition. This scope is only valid in the context of a web-based Spring ApplicationContext . |
|
In an HTTP Session , a bean definition corresponds to an instance. This scope is only valid in the context of a web-based Spring ApplicationContext . |
|
In a global HTTP Session , a bean definition corresponds to an instance. Typically, this only works when using the portlet context. This scope is only valid in the context of a web-based Spring ApplicationContext . |
UserService userService = (UserService)factory.getBean("userService");
userService.sayHello();
package com.myBeanPostProcessor; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor; /** * Created by balfish on 15-3-29. */
class MyBeanPostProcessor implements BeanPostProcessor { @Override
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException { System.out.println("postProcessBeforeInitialization 函数被调用");
return o;
}
@Override
public Object postProcessAfterInitialization(Object o, String s) throws BeansException { System.out.println("postProcessAfterInitialization 函数被调用");
return o;
} }
applicationContext.xml的变化
<!--配置自己的后置处理器,类似过滤器-->
<bean id="myBeanPostProcessor"
class="com.myBeanPostProcessor.MyBeanPostProcessor" />
应用场景举例
1 记录每个对象实例化的时间
2过滤每个调用ip
3 Add attributes to all objects, or functions (aop for aspect)