承接上文
自定义对象行为
.net篇(环境为vs2012+Spring.Core.dll v1.31)
public class lifeCycle : Spring.Objects.Factory.IInitializingObject, System.IDisposable, Spring.Objects.Factory.IObjectFactoryAware, Spring.Objects.Factory.IObjectNameAware { public Spring.Objects.Factory.IObjectFactory OFactory { get; set; } public String Name { get; set; } public void initMethod(){} public void destroyMethod() {} public void AfterPropertiesSet(){ initMethod(); } public void Dispose(){ destroyMethod(); } public Spring.Objects.Factory.IObjectFactory ObjectFactory{ set { OFactory = value; } } public string ObjectName{ set { Name = value; } } } public class CustomFactory : Spring.Objects.Factory.IFactoryObject { public object GetObject(){ return "1"; } public bool IsSingleton{ get { return false; } } public Type ObjectType{ get { return typeof(string); } } }
<object id="lifeCycle" type="SpringBase.lifeCycle, SpringBase" init-method="initMethod" destroy-method="destroyMethod" /> <object id="customFac" type="SpringBase.CustomFactory, SpringBase"/>
java篇(环境为Maven+Jdk1.7+IntelliJ IDEA 12.1.4)
package springdemo; import org.springframework.beans.BeansException; import org.springframework.beans.factory.*; public class LifeCycle implements InitializingBean, DisposableBean, BeanFactoryAware, BeanNameAware { private BeanFactory oFactory; private String name; public void initMethod(){} public void destroyMethod() {} @Override public void afterPropertiesSet() throws Exception { initMethod(); } @Override public void destroy() throws Exception { destroyMethod(); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { oFactory=beanFactory; } @Override public void setBeanName(String name) { this.name=name; } public String getName() { return name; } public BeanFactory getoFactory() { return oFactory; } } class CustomFactory implements FactoryBean<String>{ @Override public String getObject() throws Exception { return "1"; } @Override public Class<?> getObjectType() { return String.class; } @Override public boolean isSingleton() { return false; } }
<bean id="lifeCycle" class="springdemo.LifeCycle" init-method="initMethod" destroy-method="destroyMethod" /> <bean id="customFac" class="springdemo.CustomFactory" />
java和Csharp的共同点
- IObjectFactoryAware|BeanFactoryAware以及IObjectNameAware|BeanNameAware 实现的接口的属性或者方法会在容器初始化完成后spring自动调用赋值,只要更改方法体即可
- IInitializingObject|InitializingBean接口的AfterPropertiesSet方法 在属性赋值完成后调用,也可以用init-method节点来和spring框架解耦
- IDisposable|DisposableBean接口的destroy方法在对象释放的时候调用, 也可以用destroy-method节点来和spring框架解耦
- IFactoryObject|FactoryBean
为创建一个工厂类, 通过id调用Ioc容器的时候返回的是getObject方法的返回值不是工厂类, 前一章节的获取对象的属性就是继承了这个接口,isSingleton返回这个对象是不是单例, ObjectType|getObjectType返回对象类型 - IObjectFactoryAware|BeanFactoryAware获取当前Ioc的容器
- IObjectNameAware|BeanNameAware获取对象在容器里面的名称
- 下一篇:Ⅷ.spring的点点滴滴--抽象对象和子对象
- 上一篇:Ⅵ.spring的点点滴滴--自定义类型转换器
- 本文链接地址:Ⅶ.spring的点点滴滴--自定义对象行为