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

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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

脚本宝典总结

以上是脚本宝典为你收集整理的Spring注解中@Bean,@Component,@Service,@Repository 和 @Controller注解的区别全部内容,希望文章能够帮你解决Spring注解中@Bean,@Component,@Service,@Repository 和 @Controller注解的区别所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。