创建Java项目,一个类是Test类 包名com.jd.test,一个类是UserInfo类 包名com.jd.vo,还有一个application.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="UserInfo" class="com.jd.vo.UserInfo" lazy-init="true" scope="prototype">
</bean>
UserInfo类
package com.jd.vo;
public class UserInfo {
public UserInfo() {
System.out.println("构造方法");
}
}
Test类
package com.jd.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext ("application.xml");
Object object = applicationContext.getBean("UserInfo");
System.out.println(object);
object = applicationContext.getBean("UserInfo");
System.out.println(object);
applicationContext.close();
}
}
运行结果:
解释代码:
scope="prototype"
①prototype 每次调用getBean()方法,获得一个新的对象
②request 用于不同请求
③session 用于不同会话,窗口
④singleton 单例,一个类里创建了对象,在这个类里就一直是这个对象
如果application.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="UserInfo" class="com.jd.vo.UserInfo" lazy-init="true" scope="singleton">
</bean>
运行结果:
注意:
scope="singleton"
单例是scope的默认值,如果不在<bean><bean/>
里添加scope属性,scope默认的就是一个容器中只能创建这一个对象。
2.22