1. 程式人生 > >@Bean、@Component、 @Service、 @Repository 和 @Controller註解的區別

@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掃描被自動檢測。