目录

​基础​

​对比​

​demo​

​配置方式​

​注解方式​


基础

​Spring系列:IOC依赖注入(根据类型查找)实例​

对比

Spring系列:ApplicationContext和BeanFactory对比区别_xml


Spring Bean 的维护和生命周期管理均在 BeanFactory 实现类中,绝多大数是指 DefaultListableBeanFactory

ApplicationContext是BeanFactory的子接口。


Spring系列:ApplicationContext和BeanFactory对比区别_spring_02




当byType是BeanFactory.class的时候,获得是的ApplicationContext中的DefaultListableBeanFactory对象。(ApplicationContext中每次getBean()都是通过DefaultListableBeanFactory来查找bean对象的)


 Spring系列:ApplicationContext和BeanFactory对比区别_xml_03



真正的IOC的底层实现就是BeanFactory的实现类,因为ApplicationContext是委托DefaultListableBeanFactory来操作getBean等方法的



demo

配置方式

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/META-INF/content-inject.xml") ;



//自定义bean
UserRepos userRepos = applicationContext.getBean("userRepos", UserRepos.class) ;

System.out.println( userRepos.getObjectFactory().getObject()== applicationContext );
System.out.println(userRepos.getBeanFactory() == applicationContext);
System.out.println(userRepos.getBeanFactory() == applicationContext.getAutowireCapableBeanFactory());

true

false

true

注解方式

package com.test;

import com.test.pojo.User;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Map;

public class IOCDemo {


public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register( IOCDemo.class) ;
applicationContext.refresh() ;
lookupBeans(applicationContext);
}

@Bean
public User user(){
User u = new User();
u.setId(1);
u.setName("NIO");
return u ;
}

private static void lookupBeans(AnnotationConfigApplicationContext beanFactory) {
if(beanFactory instanceof ListableBeanFactory){
Map<String,User> users = beanFactory.getBeansOfType(User.class);
System.out.println(users);
}
}




}

{user=User{id=1, name='NIO'}}