使用工具 idea+maven 3.6+jdk1.8
注入将基于Xml进行实现
step.1
添加倚赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
</dependencies>
step.2
创建服务类:
- 创建接口MessageService
package com.zt.spring.test002.service;
public interface MessageService {
String getMessage();
}
- 创建接口实现类MessageServiceImpl
package com.zt.spring.test002.service;
public class MessageServiceImpl implements MessageService {
private String username;
private int age;
public MessageServiceImpl(String username, int age) {
this.username = username;
this.age = age;
}
public String getMessage() {
return "Hello World! " + username + ", age is " + age;
}
}
step.3
创建打印器:MessagePrinter
package com.zt.spring.test002;
import com.zt.spring.test002.service.MessageService;
public class MessagePrinter {
final private MessageService service;
public MessagePrinter(MessageService service) {
this.service = service;
}
public void printMessage() {
System.out.println(this.service.getMessage());
}
}
- 其中在printMessage方法执行后,消息内容应该直接打印出来,而消息来源既是MessageService,这里将通过xml将该类的实现改为注入
step.4
创建应用主类:
package com.zt.spring.test002;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Application {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.printMessage();
}
}
- 其中ClassPathXmlApplicationContext是上下文的一种实现,可基于xml进行配置
- 而按照约定spring.xml要放在应用的resources下;
step.5
创建配置文件:spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 定义 bean -->
<bean id="messageServiceImpl" class="com.zt.spring.test002.service.MessageServiceImpl">
<constructor-arg name="username" value="s_zero" />
<constructor-arg name="age" value="20" />
</bean>
<bean id="messagePrinter" class="com.zt.spring.test002.MessagePrinter">
<constructor-arg name="service" ref="messageServiceImpl" />
</bean>
</beans>
- 从bean的配置中分析倚赖关系:messageServiceImpl有两个参数name和age,它们的值将在实例化时就解析完毕
- 而messagePrinter引用了messageServiceImpl作为其构造函数的参数
运行主类输出:Hello World! s_zero, age is 20
实例结构如下: