弹簧 @组件

使用 Spring Component 注释来表示一个类为 Component. 这意味着 Spring framework将自动检测这些类为 依赖注射当使用注释为基础的配置和类路径扫描。

春季组件

在俗语中,一个组件对某些操作负责,而春节框架则提供了其他三个具体的注释,用于标记一个类为组件。

我们的实用类可以被标记为服务类 2.存储库:此注释表明该类涉及CRUD操作,通常用于处理数据库表 的(DAO)(/community/tutorials/dao-design-pattern)实施 3.控制器:主要用于(web applications)(/community/tutorials/spring-mvc-example)或(REST web services)(/community/tutorials/spring-rest-example-tutorial-spring-restful-web services)来指定该类是前置控制器,负责处理用户请求并返回适当的响应

请注意,所有这四个注释都包含在org.springframework.stereotype包中,并且是spring-context罐的一部分。

春季元素示例

让我们创建一个非常简单的 Spring maven 应用程序来展示 Spring Component 注释的使用,以及 Spring 如何通过注释式配置和类路径扫描自动检测它。

1<dependency>
2    <groupId>org.springframework</groupId>
3    <artifactId>spring-context</artifactId>
4    <version>5.0.6.RELEASE</version>
5</dependency>

这就是我们需要获得春季框架核心功能的全部。让我们创建一个简单的组件类,并用@Component注释来标记它。

 1package com.journaldev.spring;
 2
 3import org.springframework.stereotype.Component;
 4
 5@Component
 6public class MathComponent {
 7
 8    public int add(int x, int y) {
 9    	return x + y;
10    }
11}

现在我们可以创建一个基于注释的春季背景,并从中获取MathComponent豆子。

 1package com.journaldev.spring;
 2
 3import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4
 5public class SpringMainClass {
 6
 7    public static void main(String[] args) {
 8    	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
 9    	context.scan("com.journaldev.spring");
10    	context.refresh();
11
12    	MathComponent ms = context.getBean(MathComponent.class);
13
14    	int result = ms.add(1, 2);
15    	System.out.println("Addition of 1 and 2 = " + result);
16
17    	context.close();
18    }
19
20}

只需运行上述类作为正常的Java应用程序,您应该在控制台中获得以下输出。

1Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
2INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 12:49:26 IST 2018]; root of context hierarchy
3Addition of 1 and 2 = 3
4Jun 05, 2018 12:49:26 PM org.springframework.context.support.AbstractApplicationContext doClose
5INFO: 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. spring component example We can also specify the component name and then get it from spring context using the same name.

1@Component("mc")
2public class MathComponent {
3}
1MathComponent ms = (MathComponent) context.getBean("mc");

虽然我使用了@Component注释,但它实际上是一个服务类,我们应该使用@Service注释。

您可以从我们的 GitHub 存储库中检查该项目。

引用: API Doc

Published At
Categories with 技术
Tagged with
comments powered by Disqus