1. 创建spring 配置文件applicationContext.xml
举例
我需要在controller层依赖注入类型为DemoService的对象demoService,将DemoService的实现类DemoServiceImpl放到spring容器中,起名为demoService,再将demoService对象依赖注入到controller中的demoService对象。
<?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">
<!-- 将DemoService的实现类DemoServiceImpl放到spring容器中,起名为demoService -->
<bean id="demoService" class="com.service.impl.DemoServiceImpl"></bean>
<!-- 在spring容器中将上面创建的demoService对象依赖注入到DemoController类中的**demoService**对象 -->
<bean id="controller" class="com.controller.DemoController">
<property name="demoService" ref="demoService"/>
</bean>
</beans>
2. 在DemoController类中创建demoService的setter方法
举例
spring xml方式的依赖注入可通过构造方法或则setter方法,我这里例子用的是setter方法 一定要有写出来。
@Controller
public class DemoController {
private DemoService demoService;
// spring xml方式的依赖注入可通过构造方法或则setter方法
// 我这里例子用的是setter方法 一定要有
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
@RequestMapping("/test")
@RespondBody
public void test() throws MyException {
// 测试代码
System.out.println(demoService);
}
}
3. 配置web.xml文件
这用于在项目启动的时候自动加载spring 的applicationContext.xml配置文件,切记!不要漏了listener!否则需要依赖注入的对象(例子中的DemoController的demoService)会因找不到spring创建的Bean对象而报空指针异常!
<!-- spring的配置开始 -->
<!-- 全局初始化参数-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring的配置结束 -->
测试结果,依赖注入成功!