Spring中的循环依赖

例子:

public class AOPTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        IndexService indexService = applicationContext.getBean(IndexService.class);
        indexService.getUserService();
    }
}


@ComponentScan("cn.jsycnqz.services")
public class AppConfig {
}


@Component
public class UserService {
    @Autowired
    IndexService indexService;

    public UserService(){
        System.out.println("Constructor from userService");
    }
}



@Component
public class IndexService {

    @Autowired
    UserService userService;

    public IndexService(){
        System.out.println("Constructor from indexService");
    }

    public void getUserService(){
        System.out.println(userService);
    }
}

 Spring的依赖注入的功能--在初始化时候完成

sprng如何初始化一个bean。        Spring 的 BeanDefinition:

@Component
public class nqzBeanFactoryPostProcessor implements BeanFactoryPostProcessor{
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        GenericBeanDefinition indexService = (GenericBeanDefinition) beanFactory.getBeanDefinition("indexService");
        indexService.setBeanClass(UserService.class);
    }
}

修改BeanDedinition来扩展spring。beanFactory.getBeanDefinition("indexService"); 实际上就是从map中取得。


 spring默认支持循环依赖。因为在spring初始化bean生命周期中,有一部是判断是是否允许循环依赖。里面判断了allowCircularReferences

private boolean allowCircularReferences = true;

 可以自己修改,为false。

AnnotationConfigApplicationContext ac = new AnnotationconfigApplicationcontext();

AbstractAutowireCapableBeanFactory beanFactory = (AbstractAutowireCapableBeanFactory)
                                                     .getBeanFactory();

beanFactory.setAllowCircularReferences(false);


ac.register(Appconfig.class);

ac.refresh();

populateBean(beanName, mbd, instanceWrapper)  会进行后置处理器调用,属性填充,也就是常常说的自动注入。

ibp.postProcessProperties()


三级缓存:

1、singletonObjects:单例池

2、singleton Factories:工厂

3、earlySingtonObjects:三级缓存

问:三级缓存put一个从二级缓存中生产出来的一个对象 为什么?

防止重复工厂重复产生bean。A(c), B(c)。不需要重复创建c。提高性能。


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值