概述
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