Spring Component注解用于将一个类标识为组件。这意味着Spring框架在使用基于注解的配置和类路径扫描时会自动检测这些类以进行依赖注入。
Spring组件
通俗地说,组件负责一些操作。Spring框架提供了另外三个特定的注解,用于在将类标记为组件时使用。
Service
:表示该类提供一些服务。我们的实用类可以被标记为Service类。Repository
:此注解表示该类处理CRUD操作,通常与处理数据库表的DAO实现一起使用。Controller
:主要与Web应用程序或REST Web服务一起使用,指定该类是前端控制器,负责处理用户请求并返回适当的响应。
请注意,所有这四个注释都在org.springframework.stereotype
包中,并且是spring-context
jar的一部分。大多数情况下,我们的组件类将属于其中三个专用注释之一,因此您可能不会经常使用@Component
注释。
Spring组件示例
让我们创建一个非常简单的Spring Maven应用程序来展示Spring组件注释的使用以及Spring如何通过基于注释的配置和类路径扫描自动检测它。创建一个maven项目并添加以下spring核心依赖项。
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
这就是我们需要获得spring框架核心功能的全部内容。让我们创建一个简单的组件类,并使用@Component
注释标记它。
package com.journaldev.spring;
import org.springframework.stereotype.Component;
@Component
public class MathComponent {
public int add(int x, int y) {
return x + y;
}
}
现在我们可以创建一个基于注释的spring上下文,并从中获取MathComponent
bean。
package com.journaldev.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringMainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
MathComponent ms = context.getBean(MathComponent.class);
int result = ms.add(1, 2);
System.out.println("Addition of 1 and 2 = " + result);
context.close();
}
}
只需像普通的java应用程序一样运行上述类,您应该在控制台中获得以下输出。
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
Addition of 1 and 2 = 3
Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
您是否意识到了Spring的强大之处,我们无需做任何事情即可将我们的组件注入到Spring上下文中。下面的图片显示了我们的Spring组件示例项目的目录结构。我们还可以指定组件名称,然后使用相同的名称从spring上下文中获取它。
@Component("mc")
public class MathComponent {
}
MathComponent ms = (MathComponent) context.getBean("mc");
尽管我在MathComponent中使用了`@Component`注解,但实际上它是一个服务类,我们应该使用`@Service`注解。结果仍将保持不变。
你可以从我们的GitHub代码库中查看该项目。
参考:API文档
Source:
https://www.digitalocean.com/community/tutorials/spring-component