1.1 准备文件 jar包
org.springframework.asm-3.0.5.RELEASE.jar
org.springframework.core-3.0.5.RELEASE.jar
org.springframework.beans-3.0.5.RELEASE.jar
org.springframework.context-3.0.5.RELEASE.jar
org.springframework.expression-3.0.5.RELEASE.jar
com.springsource.org.apache.log4j-1.2.15.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.commons.collections-3.2.1.jar
1.2. create java project
open eclipse-> new java project -> build path -> add jars -> ok
create interface:
package com.myspring.helloworld;
public interface HelloApi {
public void sayHelo();
}
create class:
package com.myspring.helloworld;
public class HelloImpl implements HelloApi{
@Override
public void sayHelo() {
System.out.println("Hello World! My first Spring Project..");
}
}
create helloworld.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<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"
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">
<!-- id 表示你这个组件的名字,class表示组件类 -->
<bean id="hello" class="com.myspring.helloworld.HelloImpl"> </bean>
</beans>
create main for test:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args){
@SuppressWarnings("resource")
BeanFactory factory = new ClassPathXmlApplicationContext("helloworld.xml");
//面向接口编程
HelloApi helloapi = factory.getBean("hello", HelloApi.class);
helloapi.sayHelo();
}
}
1.3 详解
- BeanFactory接口实现了Ioc基本的功能
- ApplicationContext接口继承自BeanFactory接口,
扩展BeanFactory的功能,例如企业级的功能(AOP集成,国际化处理)
- XmlBeanFactory:BeanFactory实现,提供基本的IoC容器功能,可以从classpath或文件系统等获取资源;
- ClassPathXmlApplicationContext:ApplicationContext实现,从classpath获取配置文件;
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath.xml");
- FileSystemXmlApplicationContext:ApplicationContext实现,从文件系统获取配置文件。
BeanFactory beanFactory = new FileSystemXmlApplicationContext("fileSystemConfig.xml");