<?xml version="1.0" encoding="GBK"?> <project name="spring" basedir="." default=""> <property name="src" value="src"/> <property name="dest" value="classes"/> <path id="classpath"> <fileset dir="../../lib"> <include name="**/*.jar"/> </fileset> <pathelement path="${dest}"/> </path> <target name="compile" description="Compile all source code"> <delete dir="${dest}"/> <mkdir dir="${dest}"/> <copy todir="${dest}"> <fileset dir="${src}"> <exclude name="**/*.java"/> </fileset> </copy> <javac destdir="${dest}" debug="true" includeantruntime="yes" deprecation="false" optimize="false" failonerror="true"> <src path="${src}"/> <classpath refid="classpath"/> <compilerarg value="-Xlint:deprecation"/> </javac> </target> <target name="run" description="Run the main class" depends="compile"> <java classname="lee.BeanTest" fork="yes" failonerror="true"> <classpath refid="classpath"/> </java> </target> </project>
<?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- 配置一个singleton Bean实例 --> <bean id="p1" class="org.crazyit.app.service.Person"/> <!-- 配置一个prototype Bean实例 --> <bean id="p2" class="org.crazyit.app.service.Person" scope="prototype"/> <bean id="date" class="java.util.Date"/> </beans>
package lee; import org.springframework.context.*; import org.springframework.context.support.*; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class BeanTest { public static void main(String[] args)throws Exception { // 以类加载路径下的beans.xml文件创建Spring容器 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // ① // 判断两次请求singleton作用域的Bean实例是否相等 System.out.println(ctx.getBean("p1") == ctx.getBean("p1")); // 判断两次请求prototype作用域的Bean实例是否相等 System.out.println(ctx.getBean("p2") == ctx.getBean("p2")); System.out.println(ctx.getBean("date")); Thread.sleep(1000); System.out.println(ctx.getBean("date")); } }
package org.crazyit.app.service; /** * Description: * <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> * <br/>Copyright (C), 2001-2016, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */ public class Person { private int age; }
来源:https://www.cnblogs.com/tszr/p/12370302.html