【Spring】 - 基于xml的两种依赖注入方式(构造函数注入,setter注入)

本文介绍了Spring框架下如何进行XML配置的依赖注入,包括通过构造函数注入(单个参数和多个参数的情况)以及setter方法注入的方式。
摘要由CSDN通过智能技术生成

概述

Spring中依赖注入 dependency injection  (DI)一般来说有两种形式: 1)基于xml的依赖注入, 2)基于注解的依赖注入。
基于xml的依赖注入方式通常又可以分为:1)构造函数方式注入。2)setter方式注入。

环境

Spring4.3.9, JDK1.8  pom添加spring依赖如下:
<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.9.RELEASE</version>
</dependency>
一个包就够了。

测试项目结构:
目的:将HelloService的实例HelloServiceImpl注入到HelloPrinter中并在Application中通过容器取出来使用。

代码如下:
HelloService接口
public interface HelloService {
	String sayHello();
}
HelloService实现
public class HelloServiceImpl implements HelloService {

	public String sayHello() {
		return "hello";
	}
	
}

HelloPrinter类(未完成版本,在这里使用不同的方法依赖注入)
public class HelloPrinter {

	private HelloService helloService;
	
	public void print() {
		System.out.println(helloService.sayHello());
	}
	
}
Application类
public class Application {
	
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("spri
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值