春天@Component
Spring的@Component注解用于将一个类标记为组件。这意味着当使用基于注解的配置和类路径扫描时,Spring框架将自动检测这些类以进行依赖注入。
春季组件
通俗来说,一个Component负责一些操作。Spring框架提供了三个其他特定的注解,用于标记一个类为Component时使用。
-
- 服务:表示该类提供一些服务。我们的实用类可以标记为服务类。
-
- 存储库:此注释表示该类处理CRUD操作,通常与处理数据库表的DAO实现一起使用。
- 控制器:主要与Web应用程序或REST Web服务一起使用,以指定该类是前控制器,负责处理用户请求并返回适当的响应。
请注意,所有这四个注解都位于org.springframework.stereotype包中,并且是spring-context jar的一部分。大多数情况下,我们的组件类将属于它的三个专门注解之一,所以你可能不会经常使用@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.Olivia.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.Olivia.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringMainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.Olivia.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

@Component("mc")
public class MathComponent {
}
MathComponent ms = (MathComponent) context.getBean("mc");
尽管我已经在MathComponent上使用了@Component注解,但实际上它是一个服务类,我们应该使用@Service注解。结果仍然是一样的。
你可以从我们的GitHub代码库中检出这个项目。
参考:API文档