小马哥课程笔记
传统 IoC 容器的实现
Java Beans 作为 IoC 容器
特性
依赖查找 生命周期管理 配置元信息 事件 自定义 资源管理 持久化 规范
JavaBeansDemo 元信息相关的不完整demo
PropertyDescriptor
import java. beans. BeanInfo ;
import java. beans. Introspector ;
import java. util. stream. Stream ;
public class BeanInfoDemo {
public static void main ( String [ ] args) throws Exception {
BeanInfo beanInfo = Introspector . getBeanInfo ( Person . class ) ;
Stream . of ( beanInfo. getPropertyDescriptors ( ) )
. forEach ( propertyDescriptor -> {
System . out. println ( propertyDescriptor) ;
} ) ;
}
}
输出
其中class属性就是在getBeanInfo要输入的stopClass
来自于Object的本地方法getClass 会被javaBeans当成一个属性 因为通常来说访问对象是要通过方法而非直接访问字段,所以会被误认为一个Property
此时只需要加上stopClass就可以防止出现这种问题
为了解决如果一个类有多层次而目标只是当前层次的情况 把父类写入到stopClass的位置
public class BeanInfoDemo {
public static void main ( String [ ] args) throws Exception {
BeanInfo beanInfo = Introspector . getBeanInfo ( Person . class , Object . class ) ;
Stream . of ( beanInfo. getPropertyDescriptors ( ) )
. forEach ( propertyDescriptor -> {
System . out. println ( propertyDescriptor) ;
} ) ;
}
}
类型配置和转换
public static void main ( String [ ] args) throws Exception {
BeanInfo beanInfo = Introspector . getBeanInfo ( Person . class , Object . class ) ;
Stream . of ( beanInfo. getPropertyDescriptors ( ) )
. forEach ( propertyDescriptor -> {
Class < ? > propertyType = propertyDescriptor. getPropertyType ( ) ;
String propertyName = propertyDescriptor. getName ( ) ;
if ( "age" . equals ( propertyName) ) {
propertyDescriptor. setPropertyEditorClass ( StringToIntegerPropertyEditor . class ) ;
}
} ) ;
}
static class StringToIntegerPropertyEditor extends PropertyEditorSupport {
public void setAsText ( String text) throws java. lang. IllegalArgumentException {
Integer value = Integer . valueOf ( text) ;
setValue ( value) ;
}
}