发表于: java/j2ee | 作者: | 日期: 2011/5/26 07:05

spring2.5提供了基于注解配置Bean的功能,这大大减少了xm文件在spring中的使用。本文总结了spring注解@Component的使用。

以下是Spring文档中对Component的解释:

org.springframework.stereotype.Component

@Target(value={TYPE})
@Retention(value=RUNTIME)
@Documented

Indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

Other class-level annotations may be considered as identifying a component as well, typically a special kind of component: e.g. the @Repository annotation or AspectJ’s @Aspect annotation.

Since:
2.5
Author:
Mark Fisher
See Also:
Repository
Service
Controller
org.springframework.context.annotation.ClassPathBeanDefinitionScanner

也就是说,使用了@Component注解的java类,spring会将其作为组件对待,如果同时配置了自动扫描的包路径,spring就会自动将其纳入到到容器中进行管理。

Spring 2.5 中除了提供 @Component 注解外,还定义了几个拥有特殊语义的注解,它们分别是:@Repository、@Service 和 @Controller。在目前的 Spring 版本中,这 3 个注解和 @Component 是等效的,但是从注解类的命名上,很容易看出这 3 个注解分别和持久层、业务层和控制层(Web 层)相对应。虽然目前这 3 个注解和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注解,而用 @Component 对那些比较中立的类进行注释。

在一个稍大的项目中,通常会有上百个组件,如果这些组件采用xml的bean定义来配置,显然会增加配置文件的体积,查找以及维护起来也不太方便。 Spring2.5为我们引入了组件自动扫描机制,他可以在类路径底下寻找标注了 @Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。它的作用和在xml文件中使用bean节点配置组件时一样的。要使用自动扫描机制,我们需要打开以下配置信息:





其中base-package为需要扫描的包(含所有子包)。

一个@Component注解示例:

SetupServer.java

public class SetupServer {
private SetupMessageHandler setupMessageHandler;
@Autowired
public void setSetupMessageHandler(SetupMessageHandler setupMessageHandler) {
this.setupMessageHandler = setupMessageHandler;
}
}

SetupMessageHandler.java

@Component
public class SetupMessageHandler extends IoHandlerAdapter {
}

以上示例中,SetupMessageHandler会被自动注入到SetupServer中。

: https://blog.darkmi.com/2011/05/26/1814.html

本文相关评论 - 才一条评论
beeshow00
2011-05-26 21:13:27

您好想请教您关于javascript 调用ocx的问题 希望您能加我QQ 1012945629 邢其玺或者发邮件给我,将万分感谢

Sorry, the comment form is closed at this time.