传统的方式:
通过new 关键字主动创建一个对象
IOC方式
对象的生命周期由Spring来管理,直接从Spring那里去获取一个对象。 IOC是反转控制 (Inversion Of Control)的缩写,就像控制权从本来在自己手里,交给了Spring。
IOC 控制反转,spring自己创建对象
DI 依赖注入,spring配置对象的属性
<property name="name" value="category 1" /> 注入c的name属性
</bean>
applicationContext.xml是Spring的核心配置文件,通过关键字c即可获取Category对象,该对象获取的时候,即被注入了字符串"category 1“到name属性中
ApplicationContext类的主要实现类是ClassPathXmlApplicationContext 和 FileSystemXmlApplicationContext
前者默认从类路径加载配置 文件,后者默认 从文件系统加载文件。
1)如果配置文件放在类路径下,直接使用ClassPathXmlApplicationContext实现类:
ApplicationContext ctx=new ClassPathXmlApplicationContext("com/techman/context/beans.xml");
这里的参数等同于:"classpath:com/techman/context/beans.xml"
2)如果配置文件在文件系统的路径下,则可以优先考虑使用FileSystemXmlApplicationContext实现类:
ApplicationContext ctx=new FileSystemXmlApplicationContext("com/techman/context/beans.xml");
这里的参数等同于:"file:com/techman/context/beans.xml".
3)如果有多个配置文件,获取ApplicationContext对象时还可以指定一组配置文件,Spring自动将多个配置文件在内存中整合成一个配置文件:
ApplicationContext ctx=new ClassPathXmlApplicationContext(new String[]{"conf/bean1.xml","conf/bean2.xml"});
或者ApplicationContext ctx=new ClassPathXmlApplicationContext("conf/bean*.xml");