Spring依赖注入
今天,我们将研究Spring依赖注入。
Spring Framework的核心概念是"依赖注入"和"面向方面的编程"。
我之前已经写过有关Java依赖注入的文章,以及如何使用Google Guice框架在我们的应用程序中自动执行此过程。
Spring依赖注入
本教程旨在通过基于注释的配置和基于XML文件的配置提供有关Spring Dependency Injection示例的详细信息。
我还将为应用程序提供JUnit测试用例示例,因为易于测试是依赖注入的主要优点之一。
我创建了spring-dependency-injection Maven项目,其结构如下图所示。
让我们一一看一下每个组件。
Spring依赖注入– Maven依赖
我在pom.xml文件中添加了Spring和JUnit Maven依赖项,最终的pom.xml代码如下。
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.theitroad.spring</groupId> <artifactId>spring-dependency-injection</artifactId> <version>0.0.1-SNAPSHOT</version> <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 Framework的当前稳定版本为4.0.0.RELEASE,而JUnit的当前版本为4.8.1,如果您使用任何其他版本,则项目进行更改的可能性很小。
如果要构建项目,则会注意到由于传递依赖项,一些其他jar也添加到了maven依赖项中,就像上面的图像一样。
Spring依赖注入–服务类
假设我们要向用户发送电子邮件和Twitter消息。
对于依赖项注入,我们需要为服务提供一个基类。
所以我有带有单个方法声明的MessageService接口,用于发送消息。
package com.theitroad.spring.di.services;
public interface MessageService {
boolean sendMessage(String msg, String rec);
}
现在,我们将有实际的实现类来发送电子邮件和Twitter消息。
package com.theitroad.spring.di.services;
public class EmailService implements MessageService {
public boolean sendMessage(String msg, String rec) {
System.out.println("Email Sent to "+rec+ " with Message="+msg);
return true;
}
}
package com.theitroad.spring.di.services;
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配置文件中提供。
package com.theitroad.spring.di.consumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import com.theitroad.spring.di.services.MessageService;
@Component
public class MyApplication {
//field-based dependency injection
//@Autowired
private MessageService service;
// constructor-based dependency injection
// @Autowired
// public MyApplication(MessageService svc){
// this.service=svc;
// }
@Autowired
public void setService(MessageService svc){
this.service=svc;
}
public boolean processMessage(String msg, String rec){
//some magic like validation, logging etc
return this.service.sendMessage(msg, rec);
}
}
关于MyApplication类的一些要点:
将@Component批注添加到该类,以便当Spring框架扫描组件时,该类将被视为组件。
@Component注释只能应用于该类,其保留策略是运行时。
如果您对Annotations保留策略不熟悉,建议您阅读Java Annotations教程。@Autowired注解用于让Spring知道需要自动装配。
这可以应用于字段,构造函数和方法。
此批注允许我们在组件中实现基于构造函数,基于字段或者基于方法的依赖项注入。对于我们的示例,我正在使用基于方法的依赖注入。
您可以取消注释构造函数方法以切换到基于构造函数的依赖项注入。
现在,让我们编写没有注释的相似类。
package com.theitroad.spring.di.consumer;
import com.theitroad.spring.di.services.MessageService;
public class MyXMLApplication {
private MessageService service;
//constructor-based dependency injection
// public MyXMLApplication(MessageService svc) {
// this.service = svc;
// }
//setter-based dependency injection
public void setService(MessageService svc){
this.service=svc;
}
public boolean processMessage(String msg, String rec) {
//some magic like validation, logging etc
return this.service.sendMessage(msg, rec);
}
}
消耗服务的简单应用程序类。
对于基于XML的配置,我们可以使用实现基于构造函数的spring依赖注入或者基于方法的spring依赖注入。
请注意,基于方法的注入方法和基于方法的注入方法是相同的,只是有些人更喜欢将其称为基于方法的注入,而有些则将其称为基于方法。
带注释的Spring依赖注入配置
对于基于注释的配置,我们需要编写一个Configurator类,该类将用于将实际的实现bean注入到组件属性中。
package com.theitroad.spring.di.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.theitroad.spring.di.services.EmailService;
import com.theitroad.spring.di.services.MessageService;
@Configuration
@ComponentScan(value={"com.theitroad.spring.di.consumer"})
public class DIConfiguration {
@Bean
public MessageService getMessageService(){
return new EmailService();
}
}
与上述程序有关的一些重要要点是:
@Configuration批注用于让Spring知道它是Configuration类。
@ComponentScan批注与@Configuration批注一起使用,以指定要查找组件类的软件包。
@Bean批注用于让Spring框架知道应使用此方法来获取要注入到Component类中的bean实现。
让我们编写一个简单的程序来测试基于注释的Spring Dependency Injection示例。
package com.theitroad.spring.di.test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.theitroad.spring.di.configuration.DIConfiguration;
import com.theitroad.spring.di.consumer.MyApplication;
public class ClientApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DIConfiguration.class);
MyApplication app = context.getBean(MyApplication.class);
app.processMessage("Hi hyman", "[email protected]");
//close the context
context.close();
}
}
AnnotationConfigApplicationContext是AbstractApplicationContext抽象类的实现,用于在使用注释时将服务自动装配到组件。
AnnotationConfigApplicationContext构造函数将Class作为参数,该参数将用于使Bean实现注入组件类。
getBean(Class)方法返回Component对象,并使用配置自动装配对象。
上下文对象是资源密集型的,因此在完成操作后应将其关闭。
当我们在程序上方运行时,将得到以下输出。
Dec 16, 2013 11:49:20 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3067ed13: startup date [Mon Dec 16 23:49:20 PST 2013]; root of context hierarchy Email Sent to [email protected] with Message=Hi hyman Dec 16, 2013 11:49:20 PM org.springframework.context.support.AbstractApplicationContext doClose INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3067ed13: startup date [Mon Dec 16 23:49:20 PST 2013]; root of context hierarchy
Spring依赖注入基于XML的配置
我们将使用以下数据创建Spring配置文件,文件名可以是任意值。
applicationContext.xml代码:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://www.springframework.org/schema/beans" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> <!-- <bean id="MyXMLApp" class="com.theitroad.spring.di.consumer.MyXMLApplication"> <constructor-arg> <bean class="com.theitroad.spring.di.services.TwitterService" </constructor-arg> </bean> --> <bean id="twitter" class="com.theitroad.spring.di.services.TwitterService"></bean> <bean id="MyXMLApp" class="com.theitroad.spring.di.consumer.MyXMLApplication"> <property name="service" ref="twitter"></property> </bean> </beans>
注意,上面的XML包含基于构造函数和基于setter的spring依赖注入的配置。
由于" MyXMLApplication"正在使用setter方法进行注入,因此bean配置包含用于注入的属性元素。
对于基于构造函数的注入,我们必须使用constructor-arg元素。
配置XML文件位于源目录中,因此在构建后将位于类目录中。
让我们看看如何通过一个简单的程序使用基于XML的配置。
package com.theitroad.spring.di.test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.theitroad.spring.di.consumer.MyXMLApplication;
public class ClientXMLApplication {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
MyXMLApplication app = context.getBean(MyXMLApplication.class);
app.processMessage("Hi hyman", "[email protected]");
//close the context
context.close();
}
}
ClassPathXmlApplicationContext用于通过提供配置文件位置来获取ApplicationContext对象。
它具有多个重载的构造函数,我们还可以提供多个配置文件。
其余代码类似于基于注释的配置测试程序,唯一的区别是我们根据配置选择获取ApplicationContext对象的方式。
当我们运行上面的程序时,我们得到以下输出。
Dec 17, 2013 12:01:23 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4eeaabad: startup date [Tue Dec 17 00:01:23 PST 2013]; root of context hierarchy Dec 17, 2013 12:01:23 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [applicationContext.xml] Twitter message Sent to [email protected] with Message=Hi hyman Dec 17, 2013 12:01:23 AM org.springframework.context.support.AbstractApplicationContext doClose INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@4eeaabad: startup date [Tue Dec 17 00:01:23 PST 2013]; root of context hierarchy
注意,某些输出是由Spring Framework编写的。
由于Spring Framework使用log4j进行日志记录,而我尚未对其进行配置,因此输出已写入控制台。
Spring依赖注入JUnit测试用例
Spring依赖注入的主要好处之一是易于拥有模拟服务类,而不是使用实际服务。
因此,我结合了以上所有知识,并将所有内容编写在一个JUnit 4测试类中,用于在Spring进行依赖项注入。
package com.theitroad.spring.di.test;
import org.junit.Assert;
import org.junit.After;
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;
import com.theitroad.spring.di.consumer.MyApplication;
import com.theitroad.spring.di.services.MessageService;
@Configuration
@ComponentScan(value="com.theitroad.spring.di.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("Mock Service");
return true;
}
};
}
@Before
public void setUp() throws Exception {
context = new AnnotationConfigApplicationContext(MyApplicationTest.class);
}
@After
public void tearDown() throws Exception {
context.close();
}
@Test
public void test() {
MyApplication app = context.getBean(MyApplication.class);
Assert.assertTrue(app.processMessage("Hi hyman", "[email protected]"));
}
}
该类使用@Configuration和@ComponentScan进行注释,因为getMessageService()方法返回了MessageService模拟实现。
这就是为什么getMessageService()带有@Bean注释的原因。
由于我正在测试配置有注释的MyApplication类,因此我使用AnnotationConfigApplicationContext并在setUp()方法中创建其对象。
上下文在tearDown()方法中关闭。
test()方法代码只是从上下文中获取组件对象并对其进行测试。

