Spring注解08 自动装配 @Autowired @Qual

2019-01-06  本文已影响0人  運河的縴夫

自动装配:

Spring利用依赖注入(DI),完成对IOC容器中中各个组件的依赖关系赋值;

自动装配用到三个注解:

@Autowired自动注入:

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

@Autowired:构造器,参数,方法,属性;都是从容器中获取参数组件的值

自定义组件想要使用Spring容器底层的一些组件(ApplicationContext,BeanFactory,xxx);

自定义组件实现xxxAware;在创建对象的时候,会调用接口规定的方法注入相关组件;Aware;
把Spring底层一些组件注入到自定义的Bean中;
xxxAware:功能使用xxxProcessor;
ApplicationContextAware==》ApplicationContextAwareProcessor;

直接鲁代码

@Configuration
@ComponentScan(value = {"com.tommy.service", "com.tommy.controller", "com.tommy.dao"})
public class AutowaireConfig {
    @Bean
    @Primary
    public PersonDao personDao(){
        final PersonDao personDao = new PersonDao();
        personDao.setLabel("2");
        return personDao;
    }
}
//名字默认是类名首字母小写
@Repository
@Data
@Primary
public class PersonDao {
    public PersonDao() {
    }
    private String label = "1";
    public Person getPerson(){
        return new Person("jm",16,"tommy");
    }
}
@Service
public class PersonService {
    // @Autowired
    //@Resource
    @Inject
    private PersonDao personDao;
    public Person getPerson() {
        return personDao.getPerson();
    }
}

测试类

public class IOCTest_Autowaire {
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AutowaireConfig.class);
    @Test
    public void testAutowaire(){
        final String[] beanNamesForType = applicationContext.getBeanDefinitionNames();
        for (String name :beanNamesForType) {
            System.out.println(name);
        }
        final Object personService = applicationContext.getBean("personService");
        System.out.println("personService "+personService);
        final PersonDao personDao = (PersonDao) applicationContext.getBean("personDao");
        System.out.println("lable "+personDao.getLabel());
    }
}
上一篇 下一篇

猜你喜欢

热点阅读