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=””>
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实例化bean的三种方式
public class University {
to
}
获取bean⽅式:
ApplicationContext ctx  = new ClassPathXmlApplicationContext("./l");
University ust = (University) Bean("university");
b.指定bean的名称
@Component("university1")
public class University {
to
}
获取bean⽅式:
ApplicationContext ctx  = new ClassPathXmlApplicationContext("./l");
University ust = (University) Bean("university1");