参考文章
版本说明
- JDK 1.7
- Spring3.2.14
org.springframework spring-context 3.2.14.RELEASE
Java项目中,启动Spring IoC、获取Bean
CLASS PATH下放一个最简单的Spring配置文件
需要由Spring托管的Bean Class
package com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean;public class DemoBean { public String test() { return "hello spring..."; }}
调用类
package com.nicchagil.springapplication.No001initSpringIocAndGetABean;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean;public class Call { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); DemoBean d1 = context.getBean("demoBean", DemoBean.class); DemoBean d2 = context.getBean("demoBean", DemoBean.class); /* execu the method*/ System.out.println(d1.test()); System.out.println(d2.test()); /* default singleton */ System.out.println("demoBean isSingleton ? -> " + context.isSingleton("demoBean")); System.out.println(d1); System.out.println(d2); System.out.println("d1 == d2 -> " + (d1 == d2)); }}
日志
hello spring...hello spring...demoBean isSingleton ? -> truecom.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean@4857b188com.nicchagil.springapplication.No001initSpringIocAndGetABean.bean.DemoBean@4857b188d1 == d2 -> true