1、首先spring的主要思想,就是依赖注入。简单来说。就是不须要手动new对象,而这些对象由spring容器统一进行管理。
2、样例结构
如上图所看到的,採用的是mavenproject。
2、pom.xml
3、spring.xml> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean /> </beans>
4、Do.javapackage com.test.pro; public class Do { public void speaking() { System.out.println("speaking......."); } }
5、測试类package com.test.pro; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml"); Do did=(Do)ctx.getBean("do"); did.speaking(); } }
6、输出
7、分析
我们能够看到,在核心的spring配置文件里的spring.xml中仅仅有一句话:<bean />,这句话指明的是有一个bean文件。名称为do,其类的地址是com.test.pro.Do。
然后就是我们的測试类里面的一段话:
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
Do did=(Do)ctx.getBean("do");
did.speaking();这里表示声明一个上下文类,这个上下文类装载了配置文件,注意,假设这里不是採用mavenproject的话,一定要注意spring.xml的相对地址。假设实在不确定相对地址是什么。能够採用绝对地址的方式。比如:
ApplicationContext ctx=new ClassPathXmlApplicationContext("file:H:/spring.xml");
然后就是利用上下文对象来获得在配置文件里声明过的bean的演示样例,而且能够直接调用。
那么这个bean文件是什么时候实例化的,假设bean的scope是prototype的,则该Bean的实例化是在第一次使用该Bean的时候进行实例化 ,能够參考这篇文章:http://www.iteye.com/problems/93479