Spring 依赖注入

 

Spring 依赖注入

 

今天我们将研究Spring Dependency InjectionSpring Framework的核心概念是“ 依赖注入 ”和“ 面向方面编程”。我之前写过关于Java依赖注入的文章,以及我们如何使用Google Guice框架在我们的应用程序中自动执行此过程。

目录[ 隐藏 ]

Spring 依赖注入

Spring 依赖注入

本教程旨在提供有关基于注释的配置和基于XML文件的配置的Spring Dependency Injection示例的详细信息。我还将为应用程序提供JUnit测试用例示例,因为易测试性是依赖注入的主要优点之一。

我创建了spring-dependency-injection maven项目,其结构如下图所示。

Spring 依赖注入

让我们逐个查看每个组件。

 

Spring依赖注入 - Maven依赖

我在pom.xml文件中添加了Spring和JUnit maven依赖项,最后的pom.xml代码如下。


<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>com.journaldev.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依赖注入 - 服务类

假设我们想要向用户发送电子邮件和推特消息。对于依赖注入,我们需要有一个服务的基类。所以我有MessageService单一方法声明接口发送消息。


package com.journaldev.spring.di.services;

public interface MessageService {

	boolean sendMessage(String msg, String rec);
}

现在我们将有实际的实现类来发送电子邮件和推特消息。


package com.journaldev.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.journaldev.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.journaldev.spring.di.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import com.journaldev.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注释只能应用于类,它的保留策略是Runtime。如果您不熟悉注释保留策略,我建议您阅读Java注释教程
  • @Autowired注释用于让Spring知道需要自动装配。这可以应用于字段,构造函数和方法。此注释允许我们在组件中实现基于构造函数,基于字段或基于方法的依赖项注入。
  • 对于我们的示例,我使用基于方法的依赖注入。您可以取消注释构造函数方法以切换到基于构造函数的依赖项注入。

现在让我们编写没有注释的类似类。


package com.journaldev.spring.di.consumer;

import com.journaldev.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依赖注入。请注意,基于方法和基于setter的注入方法是相同的,只是有些人更喜欢将其称为基于setter,有些人则称之为基于方法。

带注释的Spring依赖注入配置

对于基于注释的配置,我们需要编写一个Configurator类,用于将实际的实现bean注入组件属性。


package com.journaldev.spring.di.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.journaldev.spring.di.services.EmailService;
import com.journaldev.spring.di.services.MessageService;

@Configuration
@ComponentScan(value={"com.journaldev.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.journaldev.spring.di.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.journaldev.spring.di.configuration.DIConfiguration;
import com.journaldev.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 Pankaj", "[email protected]");
		
		//close the context
		context.close();
	}

}

AnnotationConfigApplicationContextAbstractApplicationContext抽象类的实现,它用于在使用注释时自动将服务自动装配到组件。AnnotationConfigApplicationContext构造函数将Class作为参数,用于将bean实现注入组件类中。

getBean(Class)方法返回Component对象,并使用该配置自动装配对象。上下文对象是资源密集型的,因此我们应该在完成后关闭它们。当我们运行上面的程序时,我们得到低于输出。


Dec 16, 2013 11:49:20 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]3067ed13: startup date [Mon Dec 16 23:49:20 PST 2013]; root of context hierarchy
Email Sent to pankaj@abc.com with Message=Hi Pankaj
Dec 16, 2013 11:49:20 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.spring[email protected]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="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-4.0.xsd">

<!-- 
	<bean id="MyXMLApp" class="com.journaldev.spring.di.consumer.MyXMLApplication">
		<constructor-arg>
			<bean class="com.journaldev.spring.di.services.TwitterService" />
		</constructor-arg>
	</bean>
-->
	<bean id="twitter" class="com.journaldev.spring.di.services.TwitterService"></bean>
	<bean id="MyXMLApp" class="com.journaldev.spring.di.consumer.MyXMLApplication">
		<property name="service" ref="twitter"></property>
	</bean>
</beans>

请注意,上面的XML包含基于构造函数和基于setter的spring依赖项注入的配置。由于MyXMLApplication使用setter方法进行注入,因此bean配置包含用于注入的属性元素。对于基于构造函数的注入,我们必须使用constructor-arg元素。

配置XML文件放在源目录中,因此它将在构建后位于classes目录中。

让我们看看如何使用简单的程序使用基于XML的配置。


package com.journaldev.spring.di.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.journaldev.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 Pankaj", "[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[email protected]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 Pankaj
Dec 17, 2013 12:01:23 AM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org[email protected]4eeaabad: startup date [Tue Dec 17 00:01:23 PST 2013]; root of context hierarchy

请注意,一些输出是由Spring Framework编写的。由于Spring Framework使用log4j进行日志记录,并且我没有对其进行配置,因此输出将被写入控制台。

Spring依赖注入JUnit测试用例

春季依赖注入的主要好处之一是易于使用模拟服务类而不是使用实际服务。所以我结合了上面的所有学习,并在一个JUnit 4测试类中编写了所有内容,以便在spring中进行依赖注入。


package com.journaldev.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.journaldev.spring.di.consumer.MyApplication;
import com.journaldev.spring.di.services.MessageService;

@Configuration
@ComponentScan(value="com.journaldev.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 Pankaj", "[email protected]"));
	}

}

该类使用@Configuration@ComponentScan注释进行注释,因为getMessageService()方法返回MessageService模拟实现。这就是为什么getMessageService()使用注释进行@Bean注释。

由于我正在测试MyApplication使用注释配置的类,因此我AnnotationConfigApplicationContext在setUp()方法中使用并创建它的对象。在tearDown()方法中关闭上下文。test()方法代码只是从上下文获取组件对象并对其进行测试。

您是否想知道Spring Framework如何进行自动装配并调用Spring Framework未知的方法。这是通过大量使用Java Reflection完成的,我们可以使用它来分析和修改运行时类的行为。

下载Spring依赖注入项目

从上面的URL下载示例Spring依赖注入(DI)项目并使用它来了解更多信息。