1.准备工作:在Eclipse中安装Spring Tools 3 Add-On for Spring Tools 4插件(先前装了Spring Tools 4)
注:先不采用最新的方式(比如maven;最新出现的springboot框架与以前框架的方式不同),而是采用传统的创建webproject的方式。所以需要3的支持插件。
(1)打开Eclipse
(2)Help->Eclipse Marketplace->在Find框检索spring
(3)Install Spring Tools 3 Add-On for Spring Tools 4
2.下载jar包:
(1)下载spring framework的jar包:
https://repo.spring.io/release/org/springframework/spring/
(2)下 载common-logging的jar包:
http://commons.apache.org/proper/commons-logging/download_logging.cgi
3.传统方式调用类:
(1)新建对象,new该类
(2)通过对象调用类中的方法
4.Spring方法:
(1)在java Resources上new->source Folder(用来存放resource相关的文件)
(2)在该文件下new->xml folder,命名为applicationContext.xml。在xml文件中定义bean(所有的bean标签都需要写在beans标签中)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="hello" class="com.demo.HelloWorld"/>
</beans>
(3)导入所需要的jar包
(4)两个类文件:
①HelloWorld.java
package com.demo;
import java.io.PrintStream;
public class HelloWorld {
public void sayHello() {
System.out.println("-----Hello World!-------------");
}
}
②App.java
package com.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
//采用非spring方式
//HelloWorld hello = new HelloWorld();
//hello.sayHello();
//s使用spring的方式
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld hello = context.getBean("hello",HelloWorld.class);
hello.sayHello();
}
}
5.项目结构: