例子:
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。提高性能。