Spring注解之@Component详细解析

@controller 控制器(注入服务)

2、@service 服务(注入dao)

3、@repository dao(实现dao访问)

4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)

   @Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理

下面写这个是引入component的扫描组件 

<context:component-scan base-package=”com.mmnc”> 

1、@Service用于标注业务层组件 
2、@Controller用于标注控制层组件(如struts中的action) 
3、@Repository用于标注数据访问组件,即DAO组件. 
4、@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注

@Component是一个元注解,意思是可以注解其他类注解,如@Controller @Service @Repository @Aspect。官方的原话是:带此注解的类看为组件,当使用基于注解的配置和类路径扫描的时候,这些类就会被实例化。其他类级别的注解也可以被认定为是一种特殊类型的组件,比如@Repository @Aspect。所以,@Component可以注解其他类注解。

源代码:

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

        //这个值可能作为逻辑组件(即类)的名称,在自动扫描的时候转化为spring bean,即相当<bean id="" class="" />中的id
                   public abstract String value();
            }

 

案例:

a.不指定bean的名称,默认为类名首字母小写university

@Component

public class University {

          to do sthing...

}

获取bean方式:

ApplicationContext ctx  = new ClassPathXmlApplicationContext("./config/applicationContext.xml");
           University ust = (University) ctx.getBean("university");

b.指定bean的名称

@Component("university1")

public class University {

          to do sthing...

}

获取bean方式:

ApplicationContext ctx  = new ClassPathXmlApplicationContext("./config/applicationContext.xml");
           University ust = (University) ctx.getBean("university1");



posted @ 2019-11-22 16:38  哈根达斯  阅读(5755)  评论(0编辑  收藏  举报