一. 基本概念
Spring Framework的核心概念是 DI(依赖注入) 和 AOP(面向切面编程)。
DI—Dependency Injection,即“依赖注入”:组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中。
注意:依赖注入不能单独存在,须在控制反转基础之上完成,用更通俗点的话来说,就是注入类里面的属性值,不能直接注入,须创建类的对象再完成注入。
理解DI的关键是:“谁依赖谁,为什么需要依赖,谁注入谁,注入了什么”,那我们来深入分析一下:
-谁依赖于谁:当然是应用程序依赖于IoC容器;
-为什么需要依赖:应用程序需要IoC容器来提供对象需要的外部资源;
-谁注入谁:很明显是IoC容器注入应用程序某个对象,应用程序依赖的对象;
-注入了什么:就是注入某个对象所需要的外部资源(包括对象、资源、常量数据)。
一. 环境搭建
maven依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>TestMavenDI</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<encoding>UTF-8</encoding>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
项目结构图:
二. Spring依赖注入–服务类
假设我们要向用户发送电子邮件和Twitter消息。对于依赖项注入,我们需要为服务提供一个基类。因此,我具有MessageService用于发送消息的单一方法声明的接口。
public interface MessageService {
boolean sendMessage(String msg, String rec);
}
我们有实现类来发送电子邮件和Twitter消息。
public class EmailService implements MessageService {
@Override
public boolean sendMessage(String msg, String rec) {
System.out.println("Email Sent to "+rec+ " with Message="+msg);
return true;
}
}
public class TwitterService implements MessageService {
public boolean sendMessage(String msg, String rec) {
System.out.println("Twitter message Sent to " + rec + " with Message=" + msg);
return true;
}
}
现在我们的服务已经准备就绪,我们可以继续使用将使用该服务的Component类。
三. Spring依赖注入–组件类
让我们为上述服务编写一个消费者类。我们将有两个消费者类-一个带有Spring注解的自动装配类,另一个没有注解和自动装配的类将在XML配置文件中提供。
@Component
public class MyApplication {
//基于成员的依赖注入
//@Autowired
private MessageService service;
// 基于构造器的依赖注入
// @Autowired
// public MyApplication(MessageService svc){
// this.service=svc;
// }
@Autowired
public void setService(MessageService svc) {
this.service = svc;
}
public boolean processMessage(String msg, String rec) {
//一些操作,如验证,日志等
return this.service.sendMessage(msg, rec);
}
}
关于MyApplication类的一些要点:
@Component注解被添加到该类中,以便当Spring框架扫描组件时,该类将被视为组件。@Component注解只能应用于类,并且其保留策略是Runtime。
@Autowired注解用于让Spring知道需要自动装配。这可以应用于字段,构造函数和方法。此批注允许我们在组件中实现基于构造函数,基于字段或基于方法的依赖项注入。
对于我们的示例,我正在使用基于方法的依赖注入。您可以取消注释构造函数方法以切换到基于构造函数的依赖项注入。
现在,让我们编写没有注释的类似类。
public class MyXMLApplication {
private MessageService service;
// 基于构造器的依赖注入
// public MyXMLApplication(MessageService svc) {
// this.service = svc;
// }
// 基于set方法的依赖注入
public void setService(MessageService svc){
this.service=svc;
}
public boolean processMessage(String msg, String rec) {
//一些操作,如验证,日志等
return this.service.sendMessage(msg, rec);
}
}
消耗服务的简单应用程序类。对于基于XML的配置,我们可以使用实现基于构造函数的spring依赖注入或基于方法的spring依赖注入。
四. 带注解的Spring依赖注入配置
对于基于注解的配置,我们需要编写一个Configurator类,该类将用于将实际的实现bean注入到组件属性中。
package com.consumer;
import com.services.EmailService;
import com.services.MessageService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(value = {"com.consumer"})
public class DIConfiguration {
@Bean
public MessageService getMessageService(){
return new EmailService();
}
}
与上述DIConfiguration 有关的一些要点是:
@Configuration 注解用于让Spring知道它是Configuration类。
@ComponentScan注解与@Configuration注解一起使用以指定要查找组件类的包。
@Bean 注解用于使Spring框架知道应使用此方法来获取要注入到Component类中的bean实现。
让我们编写一个简单的程序来测试基于注释的Spring Dependency Injection示例。
public class ClientApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DIConfiguration.class);
MyApplication app = context.getBean(MyApplication.class);
app.processMessage("锦瑟无端五十弦", "lisahngyin@abc.com");
//关闭上下文
context.close();
}
}
AnnotationConfigApplicationContext是AbstractApplicationContext抽象类的实现,用于在使用注解时将服务自动装配到组件。AnnotationConfigApplicationContext构造函数将Class作为参数,用于获取Bean实现以注入组件类。
getBean(Class)方法返回Component对象,并使用配置自动装配对象。上下文对象是资源密集型的,因此在完成操作后应将其关闭。当我们在程序上方运行时,将得到以下输出。
五. Spring依赖注入基于XML的配置
我们将使用以下数据创建Spring配置文件,文件名可以是任何文件。
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--<bean id="MyXMLApp" class="com.consumer.MyXMLApplication">-->
<!-- <constructor-arg>-->
<!-- <bean class="com.services.TwitterService"/>-->
<!-- </constructor-arg>-->
<!--</bean>-->
<bean id="twitter" class="com.services.TwitterService"></bean>
<bean id="MyXMLApp" class="com.consumer.MyXMLApplication">
<property name="service" ref="twitter"></property>
</bean>
</beans>
注意,上面的XML包含基于构造函数和基于setter的spring依赖注入的配置。由于MyXMLApplication正在使用setter方法进行注入,因此Bean配置包含用于注入的属性元素。对于基于构造函数的注入,我们必须使用constructor-arg元素。
配置XML文件位于源目录中,因此在构建后将位于类目录中。
让我们看看如何通过一个简单的程序使用基于XML的配置。
public class ClientXMLApplication {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MyXMLApplication app = context.getBean(MyXMLApplication.class);
app.processMessage("云想衣裳花想容", "libai@abc.com");
//关闭上下文
context.close();
}
}
ClassPathXmlApplicationContext用于通过提供配置文件位置来获取ApplicationContext对象。它具有多个重载的构造函数,我们还可以提供多个配置文件。
其余代码与基于批注的配置测试程序相似,唯一的区别是我们根据配置选择获取ApplicationContext对象的方式。
当我们运行上面的程序时,我们得到以下输出。
注意,某些输出是由Spring Framework编写的。由于Spring Framework使用log4j进行日志记录,而我尚未进行配置,因此输出已写入控制台。
六. Spring依赖注入JUnit测试用例
Spring依赖注入的主要好处之一是易于拥有模拟服务类,而不是使用实际服务。
因此,我结合了以上所有知识,并将所有内容编写在一个JUnit 4测试类中,用于在春季进行依赖项注入。
import com.consumer.MyApplication;
import com.services.MessageService;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author Guan
* @version 1.0
* @date 2021/1/13 17:54
* @purpose :
*/
@Configuration
@ComponentScan(value = "com.consumer")
public class MyApplicationTest {
private AnnotationConfigApplicationContext context = null;
@Bean
public MessageService getMessageService() {
return new MessageService(){
public boolean sendMessage(String msg, String rec) {
System.out.println("发送成功");
return true;
}
};
}
@Before
public void setUp() {
context = new AnnotationConfigApplicationContext(MyApplicationTest.class);
}
@After
public void tearDown() {
context.close();
}
@Test
public void test() {
MyApplication app = context.getBean(MyApplication.class);
Assert.assertTrue(app.processMessage("路漫漫其修远兮", "quyuan@abc.com"));
}
}
该类用@Configuration和@ComponentScan注释,因为getMessageService()方法返回MessageService模拟实现。这就是为什么getMessageService()使用注释进行@Bean注释的原因。
由于我正在测试MyApplication配置有注释的类,因此我AnnotationConfigApplicationContext在setUp()方法中使用并创建它的对象。上下文在tearDown()方法中关闭。test()方法代码只是从上下文中获取组件对象并对其进行测试。
参考链接:
链接: Pankaj-spring-DI.