扩展对象:ApplicationContext 优先选择,功能强大比beanfactory
特点
1.预先加载,把对象全部实例化到容器中 2.提供了很多接口(对国际化,事件模型,自动注册等工具)
让容器对我们的bean对象大小改写的例子 写类实现BeanPostPorcessor接口,有初始化之前和初始化之后两个方法 是容器提供的接口,对这两个方法实现我们自己的想法,把容器提供的参数bean对象转成我们的bean类型,容器就会调用。
if(bean instanceof AccountBean){ AccountBean acc=(AccountBean)bean; //也可以是bean代理对象 acc.setName(); } return acc;
在xml中,只声明一下我们写的那个类即可,容器会自动注册的。 <bean class="xxx.我们写的那个类"/> 在作测试类时,用ApplicationContext对象 ApplicationContext factory=new ClassPathXmlApplicationContext("beans/beans.xml");
beanfactory后期处理 BeanfactoryPostProcessor接口类
提供的支持工具1.对属性文件支持 (把经常变化的属性放到属性文件中,便宜维护系统) PropertyPlaceHolderConfigurer 替换后面的值 PropertyOverrideConfigurer 覆盖一个新的 可以加一个新的 操作:
(1)先建立一个属性文件model.properties 格式: name=tarena
(2)在xml中配置注册一下这个文件 <bean class="org.springframework.beans.PropertyPlaceHolderConfigurer"> //或者用PropertyOverrideConfigurer <property name="locations"> <list> <value>包/model.properties</value> </list> </property></bean> (3) 在xml中的name 的value 用${name}得到值
2.对属性编辑器的支持(当属性类型不能简单转换时用到) customEditorConfigurer 操作:
1.创建一个编辑器类,我们继承一个父类PropertyEditorSupport 覆盖两个方法:输入和输出 2.在xml中配置编辑器 <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="beanfactorypostprocessor.Address"> <bean class="beanfactorypostprocessor.AddressEditor"/> </entry> </map> </property> </bean>
事件模型:
由容器发出事件, applicationContext.publishEvent(new MyApplicationEvent) 在修改属性数据时,想让容器同步数据,则在这个方法中加入上面这个调用。 但是这个方法所在类要实现ApplicationContextAware 它提供的方法是setApplicationContext(ApplicationContext context) 获得容器的上下文对象 还要写MyApplicationEvent 继承ApplicationEvent 来封装实件源 在构造方法中调用资源 super(source) 在xml中声明我们写的bean对象 观察者监听 则要实现接口ApplicationListener 接口的方法由容器调用onApplicationEvent(ApplicationEvent event){ if(event instanceof MyApplicationEvent){ 写出事件的处理 } }
国际化 i18n
ApplicationContext中的方法: getMessage(String key,object[] args,Locale locale)//获得消息 locale 指定区域 ResourceBundleMessageSource 注册消息源指定那个资源文件(baseNames) 操作:1.创建消息资源文件 show=this is show= /u3404/u3783/ 这是公司 xxx_ZH_CN // show=this{0}is{1}tarena 用于插入 用native2ascii在命令行回车,把汉字打上再回车即可 2.在测试类中,调用getMessage("show",null,Locale.CHINA) //getMessage("show",new String[]("-","*"),Locale.US) 用于插入消息中 3.在xml中加上消息注册配置 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>i18n/model</value> </list> </property>
AOP 面向方面 重复代码问题