第一步:创建javaweb项目
第二步:导入必要的IOC包,这儿有五个
“commons-logging.jar”
“spring-beans-3.2.8.RELEASE.jar”
“spring-context-3.2.8.RELEASE.jar”
“spring-core-3.2.8.RELEASE.jar”
“spring-expression-3.2.8.RELEASE.jar”
第三步:导入spring配置文件,我这儿是applicationContext.xml,
由于spring实例化bean有三种方式
第一种:利用构造器实例化bean
<!-- 通过构造器实例化bean -->
<!-- class是需要创建bean的类名,id是别名,用来获取该bean -->
<bean id="obj" class="java.util.GregorianCalendar">
</bean>
第二种:静态工厂创建bean
<!-- 通过静态工厂方法来创建bean -->
<!-- class是工程类的类名
factory-method是静态方法名,静态方法不能直接创建对象,该静态工厂方法返回的对象就是我们需要的对象 -->
<bean id="obj2" class="java.util.Calendar" factory-method="getInstance"/>
第三种:实例工厂来创建bean
<!-- 创建工厂 -->
<bean id = "obj3" class="java.util.GregorianCalendar"/>
<!-- 通过工厂方法创建对象 -->
<!-- factory-bean是实例工厂的别名
factory-method所创建的bean就是我们说需要的bean
-->
<bean id="obj4" factory-bean="obj3" factory-method="getTime" />
第四步:写测试代码(注意这个就需要导入Junit 4的包)
@Test
public void test2(){
//用容器实例化bean
String conf = "applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(conf);
//获取对象
GregorianCalendar obj =
ctx.getBean("obj",GregorianCalendar.class);
System.out.println(obj);
GregorianCalendar obj2 =
ctx.getBean("obj2",GregorianCalendar.class);
System.out.println(obj2);
Date obj4 =
ctx.getBean("obj4",Date.class);
System.out.println(obj4);
}
第五步:测试结果:
java.util.GregorianCalendar[time=1476188917115,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id=”Asia/Shanghai”,offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=9,WEEK_OF_YEAR=42,WEEK_OF_MONTH=3,DAY_OF_MONTH=11,DAY_OF_YEAR=285,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=8,HOUR_OF_DAY=20,MINUTE=28,SECOND=37,MILLISECOND=115,ZONE_OFFSET=28800000,DST_OFFSET=0]
java.util.GregorianCalendar[time=1476188917151,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id=”Asia/Shanghai”,offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=9,WEEK_OF_YEAR=42,WEEK_OF_MONTH=3,DAY_OF_MONTH=11,DAY_OF_YEAR=285,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=8,HOUR_OF_DAY=20,MINUTE=28,SECOND=37,MILLISECOND=151,ZONE_OFFSET=28800000,DST_OFFSET=0]
Tue Oct 11 20:28:37 CST 2016