Spring 常见注解记录和比较

Spring 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和 @Controller。
在目前的 Spring 版本中,这 3 个注释和 @Component 是等效的,可是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。java

从源码能够看出来没有任何区别(起码目前的版本是这样)web

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

	/**
	 * 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
	 */
	String value() default "";

}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {

	/**
	 * 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
	 */
	String value() default "";

}

关系以下spring

bean的注入方式app

@Autowired @Resource @Qualifier的区别:spa

@Autowired 根据类型注入(不指定name的状况下,使用这个更快,由于一次查询).net

@Resource 默认根据名字注入,其次按照类型搜索(指定名字的状况下根据name定位更快,若是不指定须要两次查询,接口有多个实现类的时候必须指定name)3d

@Autowired @Qualifie("userService") 两个结合起来能够根据名字和类型注入(若是选择了Autowire,接口有多个实现类的时候,必须搭配@Qualifile)code

简单记录,我查看的spring版本为2.5component

/**
 * Indicates that an annotated class is a "Controller" (e.g. a web controller).
 *
 * <p>This annotation serves as a specialization of {@link Component @Component},
 * allowing for implementation classes to be autodetected through classpath scanning.
 * It is typically used in combination with annotated handler methods based on the
 * {@link org.springframework.web.bind.annotation.RequestMapping} annotation.
 *
 * @author Arjen Poutsma
 * @author Juergen Hoeller
 * @since 2.5
 * @see Component
 * @see org.springframework.web.bind.annotation.RequestMapping
 * @see org.springframework.context.annotation.ClassPathBeanDefinitionScanner
 */
相关文章
相关标签/搜索