Skip to content
Open
Changes from 2 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
27 changes: 22 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,22 @@ 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方法。

- 这里的 `MyPersonComponent` 用处:生成`MyServiceImpl` 的Bean对象,代替了 XML 的绝大部分工作,该类本身是和`MyServiceImpl`无关的(没有继承)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这段跟前面一段我大概知道你想表达是什么了,但感觉文字上可以再梳理一下,现在读起来逻辑上感觉有点乱。

前面在讲 该类本身是和MyServiceImpl无关的(没有继承),后面说 而之前的三种 依赖注入(DI) 方式都是通过 XML 来生成,这没有逻辑上的对应性。。。

- 而之前的三种 依赖注入(DI) 方式都是通过 XML 来生成 `MyServiceImpl` 的Bean对象,类运行时就是 Bean 对象

```Java
Main函数中的例子(命名稍微改动,请变通):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个代码例子是从前面 IoC 那部分拿的吗?我没太懂想表达什么意思...

ApplicationContext ComponentContext = new ClassPathXmlApplicationContext("Component-scan.xml");
MyServiceImpl service = ComponentContext.getBean("myService", MyServiceImpl.class);
System.out.println(service.sayHello());
```