深入理解Spring IoC容器和动态代理机制

时间:2023-03-09 22:14:59
深入理解Spring IoC容器和动态代理机制

Deployment期间验证

实现一:

     <bean id="theTargetBean" class="..."/>

     <bean id="theClientBean" class="...">
<property name="targetName">
<idref bean="theTargetBean" />
</property>
</bean>

实现二:

     <bean id="theTargetBean" class="..." />

     <bean id="client" class="...">
<property name="targetName" value="theTargetBean" />
</bean>

方式1跟方式2得到的依赖关系完全一致,不同的是方式1在deployment的时候就会去判断名字为theTargetBean的bean是否有定义,方式2要推迟到client被实例化的时候才去判断名字为theTargetBean的bean是否有定义。

XML简写
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
命名空间p表示可以将<property>变成属性p:[name|name-ref]=”id”的方式出现于<bean>定义中;
命名空间c表示可以将<constructor-arg>变成属性c:[name|name-ref]=”id”的方式出现<bean>定义中;

提前初始化
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
<bean name="not.lazy" class="com.foo.AnotherBean"/>
缺省情况下ApplicationContext在Initialization Process的时候就会创建并配置所有Singleton Bean (没有依赖项的bean),如果lazy-init显示设置为true则表示取消提前初始化的功能,从而加快初始化速度并减少内存占用;对于<beans/>使用default-lazy-init=”true”属性进行批量设置。

方法注入(Lookup Method Injection)

Java代码

 public abstract class CommandManager {
protected abstract Command createCommand();
}

Xml代码

 <bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
<!-- inject dependencies here as required -->
</bean> <bean id="commandManager" class="fiona.apple.CommandManager">
<lookup-method name="createCommand" bean="command"/>
</bean>

CommandManager中的createCommand方法根据不同要求需要不同的实现,通过配置文件的<lookup-method>可以指定不同bean定义的方法实现;如果一个bean是stateful的则需要将scope设置为prototype,在每次调用的时候都生成一个新的instance。
<lookup-method/>标签用于解决当一个singleton的Bean A需要引用另外一个非singleton的Bean B(也就是每一次引用Bean B都需要引用最新创建的实例);实现方式是动态创建一个CommandManager的子类,并复写指定的方法;
AOP综合使用JDK Dynamic Proxy和CGLIB对目标类进行代理,两者区别如下:
#1 JDK Dynamic Proxy方式使用Java Reflection技术,因此要求目标类有一个Interface,并且目标方法需要此Interface中申明,动态创建一个实现了Interface的类并在改类中调用目标类的方法;

 public class PerformanceMonitorProxy implements InvocationHandler {

     private Object target;

     public ServiceWithPerformanceMonitorProxy(Object target) {
this.target = target;
} public static Object newProxyInstance(Object target) {
Class clazz = target.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(),
new ServiceWithPerformanceMonitorProxy(target));
} @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//do something before target function invocation
PerformanceMonitor.begin(method.getName());
Object result = method.invoke(target, args);
//do something after target function invocation
PerformanceMonitor.end(method.getName());
return result;
}
}

#2 CGLIB使用字节码技术,动态生成一个目标类的子类,通过over-write去覆盖目标方法;

 public class CGlibProxy implements MethodInterceptor {
private Enhancer enhancer = new Enhancer();
public Object getProxy(Class clazz) {
enhancer.setSuperclass(clazz);
enhancer.setCallback(this); // 代理执行时会回调此this持有的intercept方法,以实现代码织入
return enhancer.create();
} @Override
public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
PerformanceMonitor.begin(method.getName());
Object result = methodProxy.invokeSuper(target, args);
// 下面这样是无法执行原有方法的,因为这里的target并不是原有类的实例,而是代理类的实例
// target :
// com.dianping.aop.AdminServiceImpl$$EnhancerByCGLIB$$225da297@16dd5a9d
// Object result = method.invoke(target, args);
PerformanceMonitor.end(method.getName());
return result;
}
}

Spring一般首选JDK Dynamic Proxy进行代理,如果遇到没有实现Interface的情况则使用CGLIB,当然可以通过下属设置强制使用CGLIB;

 <aop:config proxy-target-class="true">
<!-- other beans defined here... -->
</aop:config>

Bean作用范围 (<bean ………. Scope=”…….” />)

Singleton:缺省值,一个Spring IoC容器中至多仅生成一个instance,被依赖者共享,stateless
Prototype:每次调用都会生成一个新的instance,不同依赖者使用不同的实例,stateful
Request:WebApplicationContext中一次HTTP请求中至多仅生成一个instance
Session:WebApplicationContext中一个HTTP Session中至多仅生成一个instance
Global Session:WebApplicationContext中一个Global HTTP Session中至多仅生成一个instance
Application:WebApplicationContext中一个ServletContext中至多仅生成一个instance

     <bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
<aop:scoped-proxy/>
</bean> <!-- a singleton-scoped bean injected with a proxy to the above bean -->
<bean id="userService" class="com.foo.SimpleUserService">
<property name="userPreferences" ref="userPreferences"/>
</bean>

<aop:scoped-proxy/>用于解决将一个shorter-lived scoped bean注入到一个longer-lived scoped bean时shorter-lived scoped bean提前失效的场景;由于singleton类仅有一次注入bean的机会,因此解决思路是在一开始就在longer-lived scoped bean(singleton)中注入一个proxy class作为代理类,如果shorter-lived scoped bean(session)已经失效,代理类会使用当前session scope的shorter-lived bean。

定制Bean的初始化和销毁动作

方法一:使用标注@PostConstruct和@PreDestroy;在bean的java类文件中添加。
这两个标注由CommonAnnotationBeanPostProcessor进行处理。

 @PostConstruct
public void init(){
System.out.println("init method”);
}
@PreDestroy
public void dostory(){
System.out.println("destory method");
}

方法二:使用xml配置属性init-method和destroy-method,或者在<beans/>中添加批量设置的属性default-init-method或者default-destroy-method;

 <bean id="initAndDestroySeqBean"
class="com.chj.spring.InitAndDestroySeqBean"
init-method="initMethod"
destroy-method="destroyMethod"/>

方法三:使用接口InitializingBean和DisposableBean (不推荐)

 public class PersonService  implements InitializingBean,DisposableBean{
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("init method");
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("init method");
}
}

执行顺序为@PostConstruct -> InitializingBean -> init-method

如果POJO需要获取容器的某些消息,可以实现下述接口;但是一旦实现这些接口之后就与Spring框架强耦合;

 public interface ApplicationContextAware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
public interface BeanNameAware {
void setBeanName(string name) throws BeansException;
}

Bean继承

当需要创建同一个class或者同一个parent class的多个不同状态的instance时,使用parent属性可以有效减少配置文件中需要填写的属性值;

 <bean id="inheritedTestBean" abstract="true"
class="org.springframework.beans.TestBean">
<property name="name" value="parent"/>
<property name="age" value="1"/>
</bean> <bean id="inheritsWithDifferentClass"
class="org.springframework.beans.DerivedTestBean"
parent="inheritedTestBean" init-method="initialize">
<property name="name" value="override"/>
<!-- the age property value of 1 will be inherited from parent -->
</bean>

#1 inheritsTestBean中的abstract=true表示当前bean不能实例化;如果一个singleton bean不打算进行实例化,则需要加上abstract=true属性。
#2 inheritsWithDifferentClass中的class属性不需要extends自parent class,但必须与parent class bean定义的属性匹配;并且可省略,表示使用parent指定bean的class属性;

Spring容器扩展点接口
BeanPostProcessor可以进行customized的实例化、初始化、依赖装配、依赖验证等流程(处理annotation标签,比如@Autowired,@Resource等)。
BeanFactoryPostProcessor可以修改xml文件的bean metadata;Ordered接口控制先后执行顺序。

自动装配(Autowiring)
XML Injection在Annotation Injection之后执行,所以前者会覆盖后者的相同设置,比如如果<property/>或者<constructor-arg/>也针对同一属性进行装配,则@Autowire装配的内容被覆盖;自动装配不能指定简单类型,如String;并且容易造成匹配歧义从而抛出异常;

 <?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> </beans>

‘<context:annotation-config>’表示使用annotation对属性进行自动装配,同时还注册了一系列post processors(比如AutowiredAnnotationBeanPostProcessor);加入上述tag之后就可以在java class中使用如下annotation了。

@Required:应用于属性的setter方法,表示相关的property必须设置值,否则抛出异常,但不检查是否为空。
@Autowired:应用于属性或者属性的setter方法, 表示相关的property必须有且仅有一个匹配项;如果应用于Spring自定义的Interface(如ApplicationContext)则容器会自动赋值匹配,无需额外进行设置;@Autowired是基于类型匹配的,所以如果一个bean是collection或者map则不能用@Autowired而需要使用@Resource。