先看一下BeanFactory接口的三个子接口:
还是很清楚的
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("输出随机整数: " + i); } }<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>
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)); } }
运行结果为: