1、安装Spring Tool Sui
登录http://spring.io/tools/sts/all 下载所需的Spring Tool Suit安装包
下载完成后
Eclipse --- Help--- Install new Sofware
点击Add按钮 ,再点击Archive 选择你刚刚下载的zip文件
选择带有“Spring IDE”字样的项,一个4个:
最好取消联网更新,否则会很慢
2、加Maven
参考http://projects.spring.io/spring-framework/
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency>
3、范例
src下新建Spring Bean Configuration File,命名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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置bean --> <bean id="helloWorld" class="com.mycompany.app.my_webapp.HelloWorld"> <property name="name" value="Colin2"></property> </bean> </beans>
全类名用反射的方式由spring创建对象,id用来标示这个对象。用name对应setter
以下是Spring前后对比:
public class App { public static void main(String[] args) { // HelloWorld helloWorld = new HelloWorld(); // helloWorld.setName("colin"); // 1、创建Spring的IOC容器对象 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // 2、从IOC容器中获取Bean实例 HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld"); // 3、 helloWorld.hello(); } }
创建容器时,他会根据配置文件,调用构造器创建相应对象,并调用setter给属性赋值
附:Maven web 依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency>