本文介绍了当用@Component注解一个类时,这是否意味着它是一个Spring Bean和Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对 Spring 还很陌生,我有一个关于注释类的问题.当用 @Component 注释一个类时,这是否意味着这个类将是一个 Spring Bean,默认情况下是一个单例?

Being fairly new to Spring I have a question about annotating a class. When annotating a class with @Component does this mean this class will be a Spring Bean and by default a singleton?

推荐答案

是的,没错,@Component 是 Spring bean 和 Singleton.

Yes, that is correct, @Component is a Spring bean and a Singleton.

如果该类属于服务层,您可能希望使用 @Service 对其进行注释

If the class belongs to the service layer you may want to annotate it with @Service instead

但请记住,为了检测到这些注释,您需要将此行放在 applicationContext.xml 中:

But have in mind that in order for these annotations to be detected, you need to place this line in applicationContext.xml:

<context:component-scan base-package="com.yourcompany" />

关于单例 - 默认情况下,spring bean 都在单例范围内.您唯一需要记住的是,您不应该将状态存储在字段变量中(它们应该只包含依赖项).因此,您的应用程序将是线程安全的,并且您不会每次都需要一个新的 bean 实例.换句话说,你的 bean 是无状态的.

About singletons - spring beans are all in singleton scope by default. The only thing you have to have in mind is that you should not store state in field variables (they should only hold dependencies). Thus your application will be thread-safe, and you won't require a new instance of a bean each time. In other words, your beans are stateless.

这篇关于当用@Component注解一个类时,这是否意味着它是一个Spring Bean和Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 21:55