Spring源码笔记

BeanFactory和FactoryBean
BeanFacotry(接口)是spring中比较原始的Factory。ApplicationContext接口,它由BeanFactory接口派生而来,ApplicationContext包含BeanFactory的所有功能,通常建议比BeanFactory优先
BeanFactory是访问IOC容器的根接口。这是bean容器的基本客户端视图;其他接口,如{ListableBeanFactory}和{org.springframework.beans.factory.config.ConfigurableBeanFactory}可用于特定目的。这个接口是由包含大量bean定义的对象实现的,
FactoryBean(接口)是用来给Spring容器注册springbean的接口,由于spring自带的注入bean比较麻烦,顾提供了用户可以通过实现该接口定制实例化Bean的逻辑
一般情况下,Spring通过反射机制利用bean的class属性指定实现类实例化Bean,在某些情况下,实例化Bean过程比较复杂,如果按照传统的方式,则需要在bean中提供大量的配置信息。配置方式的灵活性是受限的,这时采用编码的方式可能会得到一个简单的方案。Spring为此提供了一个org.springframework.bean.factory.FactoryBean的工厂类接口,用户可以通过实现该接口定制实例化Bean的逻辑。FactoryBean接口对于Spring框架来说占用重要的地位,Spring自身就提供了70多个FactoryBean的实现。
//当这个类进入spring容器时,会注册重写方法中的对象
//这里Component中指定的name就是方法中返回对象的id
@Component("user")
public class MinXuFactoryBean implements FactoryBean {
@Override
public Object getObject() throws Exception {
return new Person();
}
@Override
public Class<?> getObjectType() {
return Person.class;
}
}
六种定义bean的方式
- bean标签
- @Bean
- @Component
- 使用BeanDefinition
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
.genericBeanDefinition().getBeanDefinition();
beanDefinition.setBeanClass(User.class);
applicationContext.registerBeanDefinition("user",beanDefinition);
applicationContext.refresh();
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
- 使用FactoryBean
当实现了FactoryBean的类进入spring容器时,
注册两个对象进入容器中,一是本身,二是方法中的对象
@Test
public void demo02() {
AnnotationConfigApplicationContext applicationContext = new
AnnotationConfigApplicationContext(Config.class);
Person person = applicationContext.getBean(Person.class);
System.out.println(person);
}
//当这个类进入spring容器时,会注册重写方法中的对象
@Component
public class MinXuFactoryBean implements FactoryBean {
@Override
public Object getObject() throws Exception {
return new Person();
}
@Override
public Class<?> getObjectType() {
return Person.class;
}
}
- 使用Supllier
applicationContext.registerBean(User.class)注册bean就和在User类上添加@Component差不多
使用Supplier函数式接口 返回一个被初始化的user对象
//如果不使用 对象属性为默认值
AnnotationConfigApplicationContext applicationContext = new
AnnotationConfigApplicationContext(Config.class);
//使用Supplier函数式接口 返回一个被初始化的user对象
//如果不使用 对象属性为默认值
applicationContext.registerBean(User.class, new Supplier<User>() {
@Override
public User get() {
User user = new User();
user.setName("闵续");
return user;
}
});
User user = applicationContext.getBean("user", User.class);
System.out.println(user);
SpringBean和直接new的区别
当User对象中有属性使用了@AutoWared时,直接new对象是不会自动注入的
BeanFactory beanFactory = new DefaultListableBeanFactory();
//如果user已被注册 此处可以获取到 如果需要依赖注入 在创建bean的时候会注入
User user = beanFactory.getBean("user", User.class);
//直接new,永远不会自动注入属性
User user1=new User();
363

被折叠的 条评论
为什么被折叠?



