spring依赖注入

spring依赖注入:spring和注入相关的注解有:autoWired,resource,qualifier,service,controller,repository,component,

autoWired:自动从spring的上下文查找bean来注入。

resource:用来指定名称来注入。

service,controller,repository用来注入服务层,控制层,数据库层,spring扫描注解时,会标记这些需要生成bean。

上面的Autowired和Resource是用来修饰字段,构造函数,或者设置方法,并做注入的。而Service,Controller,Repository,Component则是用来修饰类,标记这些类要生成bean。

        ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation");
        CarService service = appContext.getBean(CarService.class);
        service.addCar("宝马");

在上面的main方法中首先我们初始化了appContext,他是AnnotationConfigApplicationContext,它的构造函数接受一个package的名称,来限定要扫描的package。

然后就可以通过appContext的getBean方法获得CarService的实例了。

    <context:annotation-config />
    <context:component-scan base-package="cn.outofmemory.helloannotation" >
    </context:component-scan>





原文地址:https://www.cnblogs.com/minshia/p/6950855.html