一、@Autowired:自动注入

1、默认优先按照类型取容器中找对应的组件:applicationContext.getBean(BookDao.class);

2、如果找到多个相同类型的组件,再将属性的名称作为组件id去容器中查找:

applicationContext.getBean("bookDao");

3、@Qualifier("bookDao"):使用@Qualifier指定需要装配的组件的id,而不是使用属性名

4、自动装配默认一定要将属性赋值好,没有就会报错;可以使用@Autowired(required=false);

5、@Primary:让Spring进行自动装配的时候默认使用首选的bean;也可以继续使用@Qualifier指定需要装配的bean的名字

二、Spring还支持使用@Resource(JSR250)和@Inject(JSR330)[java规范的注解]

@Resource:

可以和@Autowired一样实现自动装配功能,默认是按照组件名称进行装配,不支持@Primary和@Autowired(required=false)

@Inject:

需要导入javax.inject包,和@Autowired功能一样,没有required=false功能

三、@Bean标注的方法创建对象的时候,方法参数值从容器中获取(@Autowired标注在方法位置,默认不写,效果一样的)

@Autowired标注在构造器上,如果组件只有一个有参构造器,这个有参构造器的@Autowired也可以默认不写

@Configuration
@ComponentScan(value={"com.suxiaodong.repository"})
public class ConfigurationBean {
    
    @Bean
    public PersonService personService(PersonRepository personRepository) {
        PersonService r = new PersonService();
        r.setPersonRepository(personRepository);
        return r;
    }
}

 四、自定义组件想要使用Spring容器底层的一些组件(ApplicationContext,BeanFactory,xxx),自定义组件实现xxxAware,在创建对象时,会调用接口规定的方法注入相关组件;Aware把Spring底层一些组件注入到自定义Bean中

   xxxAware:功能使用xxxProcess(后置处理器):

  ApplicationContextAware ==>ApplicationContextAwareProcessor

public class Person implements ApplicationContextAware, BeanNameAware,
        EmbeddedValueResolverAware {
    private ApplicationContext applicationContext;

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        String resolve = resolver.resolveStringValue("你好,${os.name},我是#{36*10}");
        System.out.println(resolve);
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("this bean name is " + name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }
}