Spring注解中@Bean,@Component,@Service,@Repository 和 @Controller注解的区别

总结

@Bean:表示一个方法实例化、配置或者初始化一个Spring IoC容器管理的新对象。
@Component: 自动被comonent扫描。 表示被注解的类会自动被component扫描
@Repository: 用于持久层,主要是数据库存储库。
@Service: 表示被注解的类是位于业务层的业务component。
@Controller:表明被注解的类是控制component,主要用于展现层 。

@Bean与@Component区别

@Component是 spring 2.5引入的,为了摆脱通过classpath扫描根据xml方式定义的bean的方式.

@Bean是spring 3.0 引入的,和 @Configuration一起工作,为了摆脱原先的xml和java config方式。

Spring管理Bean方式有两种,一种是注册Bean,一种装配Bean。
可以通过三种方式实现bean管理,一使用自动配置的方式、二使用JavaConfig的方式、三使用XML配置的方式。

@Compent 作用就相当于 XML配置

@Component
@Data
public class User{
    private String name = "tom";
}

@Bean 需要在配置类中使用,即类上需要加上@Component或者@Configuration注解, 通常加上@Configuration。 @Bean的用法在这里。

@Configuration
public class AppConfig {

    @Bean
    public TransferServiceImpl transferService() {
        return new TransferServiceImpl();
    }
}

官方文档在这里

两者都可以通过@Autowired装配

@Autowired
private TransferService transferService;

@Component与@Service区别

目前基本没有区别。
参看源代码spring-context-4.3.16

/**
 * Indicates that an annotated class is a "Service", originally defined by Domain-Driven
 * Design (Evans, 2003) as "an operation offered as an interface that stands alone in the
 * model, with no encapsulated state."
 *
 * <p>May also indicate that a class is a "Business Service Facade" (in the Core J2EE
 * patterns sense), or something similar. This annotation is a general-purpose stereotype
 * and individual teams may narrow their semantics and use as appropriate.
 *
 * <p>This annotation serves as a specialization of {@link Component @Component},
 * allowing for implementation classes to be autodetected through classpath scanning.
 *
 * @author Juergen Hoeller
 * @since 2.5
 * @see Component
 * @see Repository
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	String value() default "";

}

从源代码可以看出@Service和@Component没啥本质区别,官方文档也说了This annotation serves as a specialization of {@link Component @Component},

allowing for implementation classes to be autodetected through classpath scanning. 也就是@Service是一种具体的@Component,使得被注解类能通过classpath扫描被自动检测。


原文链接:https://blog.csdn.net/russle/article/details/83247163

posted @   爱我的幸运  阅读(1717)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示