HelloBean.java |
package javamxj.spring.basic.singleton; public class HelloBean { private String helloWorld; private int i = (int) (100 * Math.random()); public HelloBean(String helloWorld) { this.helloWorld = helloWorld; } public void sayHello() { System.out.println(helloWorld); System.out.println("輸出隨機(jī)整數(shù): " + i); } } |
bean.xml |
<?xml version="1.0" encoding="GBK"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="singletonBean" class="javamxj.spring.basic.singleton.HelloBean"> <constructor-arg> <value>Hello! 這是singletonBean!</value> </constructor-arg> </bean> <bean id="prototypeBean" class="javamxj.spring.basic.singleton.HelloBean" singleton="false"> <constructor-arg> <value>Hello! 這是prototypeBean! </value> </constructor-arg> </bean> </beans> |
Main.java |
package javamxj.spring.basic.singleton; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class Main { public static void main(String[] args) { Resource res = new ClassPathResource("javamxj/spring/basic/singleton/bean.xml"); BeanFactory factory = new XmlBeanFactory(res); HelloBean h1 = (HelloBean) factory.getBean("singletonBean"); h1.sayHello(); HelloBean h2 = (HelloBean) factory.getBean("singletonBean"); h2.sayHello(); System.out.println("h1==h2: " + (h1==h2)); System.out.println(""); HelloBean h3 = (HelloBean) factory.getBean("prototypeBean"); h3.sayHello(); HelloBean h4 = (HelloBean) factory.getBean("prototypeBean"); h4.sayHello(); System.out.println("h3==h4: " + (h3==h4)); } } |
聯(lián)系客服