- request
- session
- global-session
三个在web开发中才有意义
如果配置成prototype有点类似于request
如果配置成singleton有点类似于web开发中的global-session
- 三种获取ApplicationContext对象引用的方法
1、ClassPathXmlApplicationContext:从类路径中加载
2、FileSystemXmlApplicationContext:从文件系统加载
3、XmlWebApplicationContext:从web系统中加载
项目结构:
beans.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="student" scope="prototype" class="com.litao.ioc.Student"> <property name="name" value="小猪" /> </bean> </beans>
Student.java
package com.litao.ioc; public class Student { private String name; //Java对象都有一个默认无参构造函数 public Student(){ System.out.println("对象被创建"); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
App1.java
package com.litao.ioc; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class App1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //通过类路径来获取 ApplicationContext ac = new ClassPathXmlApplicationContext("com/litao/ioc/beans.xml"); //通过文件路径来获取,通过相对路径或绝对路径 //ApplicationContext ac = new FileSystemXmlApplicationContext("beans.xml"); //当tomcat启动的时候会去加载 //ApplicationContext ac = new 3.XmlWebApplicationContext(""); Student s1 = (Student)ac.getBean("student"); Student s2 = (Student)ac.getBean("student"); System.out.println(s1+" "+s2); //配置成prototype,如果不使用则不给你创建对象,每次会产生全新的对象,对象的内存地址不一样 //配置singleton,如果不使用则会给你创建一个,不管使用多少次都是同一个对象,内存地址一样 } }