spring bean,java bean和对象的区别
java bean(如下代码,所有的属性私有,对外提供getset方法):
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
spring bean的定义方式:
- 声明式
1.@Component
2.@Bean
3.< bean > - 编程式
1.BeanDefinition
特殊例子:public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(); ac.register(AppConfig1.class); AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition(); beanDefinition.setBeanClass(UserService.class); ac.registerBeanDefinition("user",beanDefinition); ac.refresh(); }
如果有以下一个类: public class MyFactoryBean implements FactoryBean { @Override public Object getObject() throws Exception { return new UserService(); } @Override public Class<?> getObjectType() { return UserService.class; } } 那么以下main方法中: public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(); ac.register(AppConfig1.class); AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition(); beanDefinition.setBeanClass(MyFactoryBean.class); ac.registerBeanDefinition("user",beanDefinition); //会生成两个bean,1.MyFactoryBean类,其中beanName为&user 2.getObject()会生产beanName为user的类 ac.refresh(); }