很遗憾,在达内培训的时候没有好好学习spring,现在只好重新学习。我不太擅于理论的讲解,所以在这就把我做实验的代码贴出来。
工具:MyEclipse8.0+spring2.0
1、首先新建普通java工程:spring1;
2、添加spring2.0的核心类库。
jar包如下图:
[img]http://dl.iteye.com/upload/attachment/348670/665dcdf3-bb71-3fea-b399-a2cebfe237cf.jpg[/img]
3、新建包结构如下图:
[img]http://dl.iteye.com/upload/attachment/348625/de79ec41-f35b-3f91-9f32-095354ac4976.jpg[/img]
编写Hello接口。该接口有一个sayHello方法。hello.java代码如下:
编写Hello的实现类:HelloImpl。实现sayHello方法,可以在控制台打印一句话:hello spring !代码如下:
配置spring的配置文件applicationContext.xml:
编写测试测试类TestHello.java
运行TestHello.java将在控制台打印如下信息:
hello spring !
hello spring !
注意,因为这个例子没有配置log4j,所以会有两行警告信息,直接无视。
工具:MyEclipse8.0+spring2.0
1、首先新建普通java工程:spring1;
2、添加spring2.0的核心类库。
jar包如下图:
[img]http://dl.iteye.com/upload/attachment/348670/665dcdf3-bb71-3fea-b399-a2cebfe237cf.jpg[/img]
3、新建包结构如下图:
[img]http://dl.iteye.com/upload/attachment/348625/de79ec41-f35b-3f91-9f32-095354ac4976.jpg[/img]
编写Hello接口。该接口有一个sayHello方法。hello.java代码如下:
package hello;
public interface Hello {
public void sayHello();
}
编写Hello的实现类:HelloImpl。实现sayHello方法,可以在控制台打印一句话:hello spring !代码如下:
package hello;
public class HelloImpl implements Hello{
public void sayHello(){
System.out.println("hello spring !");
}
}
配置spring的配置文件applicationContext.xml:
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="hello" class="hello.HelloImpl"></bean>
</beans>
编写测试测试类TestHello.java
package test;
import hello.Hello;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class TestHello {
public static void main(String[]args){
/**
* bean有两种获取方式:BeanFactory、ApplicationContext
* BeanFactory
* 缺省延迟实例化bean
* ApplicationContext
* 缺省预先实例化bean
* 3种实现:加载资源的位置不同
* ClassPathXmlApplicationContext
* FileSystemXmlApplicationContext
* XmlWebApplicationContext
*/
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory bf=new XmlBeanFactory(resource);
Hello hello1=(Hello)bf.getBean("hello");
hello1.sayHello();
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello2=(Hello)ac.getBean("hello");
hello2.sayHello();
}
}
运行TestHello.java将在控制台打印如下信息:
hello spring !
hello spring !
注意,因为这个例子没有配置log4j,所以会有两行警告信息,直接无视。