spring-自动装配(一)

306 阅读2分钟

自动装配可以通过如下注解方式:

  • @Autowired
  • @Resource
  • @Inject

一、@Autowired

@Autowired是spring的方式来进行自动注入,默认优先按照属性的类型,从spring容器当中获取对应的对象:applicationContext.getBean(PersonDao.Class)。

如果spring容器当中存在多个同一类型的对象,那么:

  1. 默认根据属性名作为id,比如属性名为personDao1,则spring将会通过applicationContext.getBean(“personDao1”)的方式来获取对应的bean。
  2. 除此之外也可以在属性上添加@Qualified(value=id名)的方式来获取对应的bean,进行注入,比如:

        @Qualifier(value = "personDao")
        @Autowired
        private PersonDao personDao1;

    此时虽然属性的名称为personDao1,但是因为使用的@Qualified中的value值为personDao,所以还是会通过id为personDao的方式去获取对应的bean对象。
  3. 通过在配置文件中,Bean对象上加@Primary的方式来确定在spring容器中存在多个类型相同的bean对象时,优先获取加了@Primary的bean作为对象注入。不过在@Qualified和@Primary都使用的情况下,还是会优先以@Qualified为准进行属性注入。

在进行@Autowired注入时,如果发现spring容器当中找不到对应的对象,那么会抛出NoSuchBeanDefinitionException异常;如果不想出现此类异常,可在@Autowired中设置required值为false,如下:

    @Autowired(required = false)
    private PersonDao personDao;

@Autowired可以标注在多个位置:属性、构造器、方法、参数。

  • 标注在属性上

    @Autowired
    private PersonDao personDao;

  • 标注在构造器上,参数会从容器当中获取,如果只有一个参数,@Autowired注解可以忽略

    @Autowired
    public PersonService(PersonDao personDao) {
        this.personDao = personDao;
    }

  • 标注在方法上,不仅仅是类当中的方法上

    @Autowired
    public void setPersonDao(PersonDao personDao) {
         this.personDao = personDao;
    }
    也可以是配置文件配置bean的方法上

    @Bean
    @Autowired
    public PersonService personService2(PersonDao personDao) {
         PersonService personService = new PersonService();
         personService.setPersonDao(personDao);
         return personService;
    }

  • 标注在参数上

    public PersonService(@Autowired PersonDao personDao) {
        this.personDao = personDao;
    }

二、@Resource

@Resource属于Java注解方式的注入,主要标注在属性上,以属性名作为id,去spring容器中查找对应的对象,它不支持@Primary以及@Autowired注解对应的所有功能。用法如下:

@Resource
private PersonDao personDao;

三、@Inject

@Inject也属于Java注解,标注在属性上,使用时需要引入java.inject依赖,其支持@Primary以及@Autowired的所有功能,不过不支持required。用法如下:

@Inject
private PersonDao personDao;