spring--第一个IOC示例程序 -- 通过id获取对象
1、创建工程,
2、导入jar包
下面四个是Spring的核心包:
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
还有两个日记包:
commons-logging-1.1.3.jar
log4j-1.2.17.jar
在工程的src目录下,添加log4j日记需要的日记配置文件 log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG,stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p[%t]-%m%n
3、 编写一个Java实体Bean对象---Person类
4、New一个Spring的配置文件(这个配置文件习惯取名叫applicationContext.xml或applicationContext.xml)
applicationContext.xml配置文件的内容如下:
5、编写Spring IOC的测试代码
运行结果如下:
问题:
1、FileSystemXmlApplicationContext怎么用?
答:newFileSystemXmlApplicationContext("src/applicationContext.xml");
2、Bean是在什么时候被创建的?
答:Bean在newClassPathXmlApplicationContext的时候会被创建。
3、如果调用getBean多次,会创建几个?
答:默认情况下,多次调用,也只会返回同一个对象实例。