web项目 spring xml配置方式依赖注入 (超详细)

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的配置结束                       -->

测试结果,依赖注入成功!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值