Spring注解 @Component,@Service,@Control

来源:互联网 发布:mac上输iphone上口令 编辑:程序博客网 时间:2024/05/18 01:22


一、定义

Spring 2.5 在 @Repository 的基础上增加了功能类似的额外三个注解:@Component、@Service、@Constroller,它们分别用于软件系统的不同层次:

  • @Component 是一个泛化的概念,仅仅表示一个组件 (Bean) ,可以作用在任何层次。
  • @Service 通常作用在业务层,但是目前该功能与 @Component 相同。
  • @Constroller 通常作用在控制层,但是目前该功能与 @Component 相同。
  • @Repository用于标注数据访问组件,即DAO组件

通过在类上使用 @Repository、@Component、@Service 和 @Constroller 注解,Spring 会自动创建相应的 BeanDefinition 对象,并注册到 ApplicationContext 中。这些类就成了 Spring 受管组件。这三个注解除了作用于不同软件层次的类,其使用方式与 @Repository 是完全相同的。

另外,除了上面的四个注解外,用户可以创建自定义的注解,然后在注解上标注 @Component,那么,该自定义注解便具有了与所 @Component 相同的功能。不过这个功能并不常用。

当一个 Bean 被自动检测到时,会根据那个扫描器的 BeanNameGenerator 策略生成它的 bean 名称。默认情况下,对于包含 name 属性的 @Component、@Repository、 @Service 和 @Controller,会把 name 取值作为 Bean 的名字。如果这个注解不包含 name 值或是其他被自定义过滤器发现的组件,默认 Bean 名称会是小写开头的非限定类名。如果你不想使用默认 bean 命名策略,可以提供一个自定义的命名策略。

二、xml配置

   <context:annotation-config />         <!-- 对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->    <context:component-scan base-package="com.xlgl.epms"/>
1.annotation-config是对标记了 Spring's @Required、@Autowired、JSR250's @PostConstruct、@PreDestroy、@Resource、JAX-WS's @WebServiceRef、EJB3's @EJB、JPA's @PersistenceContext、@PersistenceUnit等注解的类进行对应的操作使注解生效。
2.base-package为需要扫描的包(含所有子包),负责扫描那些类有注解。

三、注入方式

controller

@Controllerpublic class UserController {}

serviceimpl
@Service("userServiceImpl")public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {}
 daoImpl
@Repositorypublic class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {}


0 0
原创粉丝点击