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
 */
相關文章
相關標籤/搜索