总结

@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扫描被自动检测。