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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM