1.配置Bean的属性和依赖关系
注入集合值:使用<list> <map> <set> <props>分别表示List、Map、Set或者Properties对象
<bean id="InjectCollections" class="com.deciphering.InjectCollections.InjectCollections">
<property name="sets">
<set>
<value>1</value>
<value>2</value>
</set>
</property>
<property name="lists">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
<property name="maps">
<map>
<entry key="1" value="1"></entry>
<entry key="2" value="2"></entry>
<entry key="3" value="3"></entry>
<entry key="4" value="4"></entry>
</map>
</property>
</bean>
2.管理Bean的生命周期
Spring容器中Bean的作用域:
- Singleton
- Prototype
- Request
- Session
- Global session
Spring提供两种方法在Bean全部属性设置成功后执行指定行为:
- 使用init-method
- 实现initializingBean接口
Spring提供两种方法在Bean实例销毁之前执行指定行为:
- 使用destory-method属性
- 实现DisposableBean接口
使用方法注入-协调作用域不同的Bean(singleton依赖prototype)
<bean id="helper" class="com.deciphering.bean.MyHelper" scope="prototype">
</bean>
<bean id="abstractLookupBean" class="com.deciphering.bean.AbstractLookupDemo">
<lookup-method name="getMyHelper" bean="helper"/>
</bean>
<bean id="standardLookupBean" class="com.deciphering.bean.StandardLookupDemo">
<property name="myHelper" ref="helper"/>
</bean>
public class StandardLookupDemo implements DemoBean {
private MyHelper myHelper;
public MyHelper getMyHelper() {
return myHelper;
}
public void setMyHelper(MyHelper myHelper) {
this.myHelper = myHelper;
}
@Override
public MyHelper getHelper() {
// TODO Auto-generated method stub
return this.myHelper;
}
@Override
public void someOperation() {
// TODO Auto-generated method stub
myHelper.doSomethingHelpful();
}
}
public abstract class AbstractLookupDemo implements DemoBean {
public abstract MyHelper getMyHelper();<span style="white-space:pre"> </span>//spring框架负责实现
@Override
public MyHelper getHelper(){
return getMyHelper();
}
@Override
public void someOperation() {
// TODO Auto-generated method stub
getMyHelper().doSomethingHelpful();
}
}
让Bean可以感知Spring容器
- 使用BeanNameAware接口
- 使用BeanFactoryAware接口、ApplicationContextAware接口
Spring的国际化支持:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" >
<list>
<value>message</value>
<!--
如果有多个资源文件,全部列举在此
-->
</list>
</property>
</bean>
//实例化ApplicationContext
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
String [] a = {"读者"};
//使用getMessage方法获得本地化信息。
//返回计算机环境默认的Locale
String hello = ctx.getMessage("hello", a, Locale.getDefault());
Object[] b = { new Date() };
String now = ctx.getMessage("now", b, Locale.getDefault());
//将两条本地化信息打印出来
System.out.println(hello);
System.out.println(now);
//认为设置成英文环境
hello = ctx.getMessage("hello", a, Locale.US);
now = ctx.getMessage("now", b, Locale.US);
//将两条英文信息打印出来
System.out.println(hello);
System.out.println(now);
//认为设置成中文环境
hello = ctx.getMessage("hello", a, Locale.CHINA);
now = ctx.getMessage("now", b, Locale.CHINA);
//将两条中文信息打印出来
System.out.println(hello);
System.out.println(now);