Spring Component 注解用于将一个类表示为 Component。代表着Spring框架将自动检测这些类依赖注入当使用基于注释的配置和类路径扫描时。
通俗地说,组件负责一些操作。 Spring 框架提供了另外三个在将类标记为组件时使用的特定注释。
-
Service
:表示该类提供一些服务。我们的实用程序类可以标记为服务类。
-
Repository
:该注解表示该类处理CRUD操作,通常与DAO处理数据库表的实现。
-
Controller
:主要与网络应用程序 or REST 网络服务指定该类是前端控制器,负责处理用户请求并返回适当的响应。
请注意,这四个注释都在包中org.springframework.stereotype
和一部分spring-context
罐。大多数时候,我们的组件类将属于其三个专门注释之一,因此您可能不会使用@Component
注释很多。
让我们创建一个非常简单的 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
豆从它。
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
Did you realized the power of Spring, we didn’t have to do anything to inject our component to spring context. Below image shows the directory structure of our Spring Component example project. We can also specify the component name and then get it from spring context using the same name.
@Component("mc")
public class MathComponent {
}
MathComponent ms = (MathComponent) context.getBean("mc");
虽然我用过@Component
使用MathComponent进行注释,它实际上是一个服务类,我们应该使用@Service
注解。结果还是一样。
您可以从我们的网站查看该项目GitHub 存储库.
参考:API Doc