1:在项目的pom.xml中加入spring框架的相关jar
在<dependencies></dependencies>
加入如下代码:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</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>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
2:实例化和初始化ApplicationContext,我们通过ContextLoaderListener来 实现,找到项目工程中的web.xml文件加入如下 的代码:
<!--初始化和实例化ApplicationContext -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</context-param>
<listener>
<description>spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
3:创建类
package com.gouzao;
public class Student {
private Teacher teacher;
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public void say() {
this.teacher.say();
System.out.println("Student say!");
}
}
package com.gouzao;
public class Teacher {
public void say() {
// TODO 自动生成的方法存根
System.out.println("Teacher say!");
}
}
4:在spring.xml 中配置bean,程序会根据spring.xml来初始化和实例化bean
<bean id="teacher" class="com.gouzao.Teacher"/>
<bean id="student" class="com.gouzao.Student">
<property name="teacher" ref="teacher"></property>
</bean>
5:添加测试类:
package com.gouzao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Demo {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//ApplicationContext 通过ClassPath找到了xml文件,实例化装载完成了ApplicationContext。这里 的第二步配置可以省略!
Student student = (Student) applicationContext.getBean("student");
student.say();
}
}
运行结果为