Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 10-Component-Scan.md #11

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions source/10-Component-Scan.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,16 @@
</beans>
```

>注意我们去掉了所有的 Bean 定义,也同时去掉了 `<context:annotation-config>`,因为 `<context:component-scan>` 默认就会打开 `<context:annotation-config>`,因此不需要再手动设置 `<context:annotation-config>`。
>注意我们去掉了所有的 Bean 定义,也同时去掉了 `<context:annotation-config>`
>因为 `<context:component-scan>` 默认就会打开 `<context:annotation-config>`,因此不需再手动设置

### Component

Spring 中定义了若干用于注册 Bean 的 Annotation,包括 `@Component` 以及继承自 `@Component` 的 `@Service` 和 `@Repository`。所谓的 component-scan 也就是告诉 Spring 去扫描标示了这些 Annotation 的类,将它们用于 Bean 的注册。 Spring 中推荐使用 `@Service` 和 `@Component` 标示逻辑和服务层的组件,使用 `@Repository` 标示持久层的组件。
Spring 中定义了若干用于注册 Bean 的 Annotation,包括 `@Component` 以及继承自 `@Component` 的 `@Service` 和 `@Repository`。
所谓的 component-scan 也就是告诉 Spring 去扫描标示了这些 Annotation 的类,将它们用于 Bean 的注册。
Spring 中推荐使用 `@Service` 和 `@Component` 标示逻辑和服务层的组件,使用 `@Repository` 标示持久层的组件。

>`@Service` 和 `@Repository` 都继承自 `@Component`,因此在 Bean 注册的层面,它们没有本质上的区别不过 `@Repository` 在持久层会有一个 exception 转换的作用,这里先略去不讲。
>`@Service` 和 `@Repository` 都继承自 `@Component`,因此在 Bean 注册的层面,它们没有本质上的区别不过 `@Repository` 在持久层会有一个 exception 转换的作用,这里先略去不讲。

创建一个新类 MyPersonComponent:

Expand Down Expand Up @@ -55,8 +58,15 @@ public class MyPersonComponent {
}
```

可以看到,我们基本就是把原先在 XML 当中的配置,挪到了 Java 代码当中。运行代码,得到和之前一样的结果
可见,我们其实就是把原先在 XML 当中的配置,挪到了 Java 代码里。运行代码,得到的结果和之前一样。

>注意到我们的 `MyServiceImpl` 仅仅设置了 greeting,为什么这样就能够正常工作呢?还记得上一节的 `@Autowired` 吗,它依然在发挥自己的作用,帮我们找到了 Person 的实例,并且赋给了 `MyServiceImpl`。
>注意到我们的 `MyServiceImpl` 仅仅设置了 greeting,为什么这样就能够正常工作呢?还记得上一节的 `@Autowired` 吗,它依然在发挥自己的作用,帮我们找到了 Person 的实例,并且赋给了 `MyServiceImpl`。


<hr>
小结一下:
> 其实这里的 `MyPersonComponent` 和之前三个 "依赖注入(DI)" 的类是完全不一样的
> 对比一下,你会发现前三种DI都是有 sayHello()方法的,而这里的 `MyPersonComponent` 只是代替了 XML 的部分工作,本身并没有 sayHello方法。

- 之前的三种 依赖注入(DI) 方式的实现都是: 由 Spring 容器通过 XML 来生成 `MyServiceImpl` 类的Bean对象(类本身就是 Spring 容器操作的对象)
- 而这里的 `MyPersonComponent` 类只是用来生成`MyServiceImpl` 的Bean对象,它是代替了 XML 的绝大部分工作(这个类是没有 sayHello方法的)