BeanFactory与FactoryBean的区别
2022-04-30 本文已影响0人
养一只tom猫
首先二者从名称上就能看到区别,BeanFactory是Spring提供的存放Bean的工厂,FactoryBean是一个可生产Bean的工厂Bean。
FactoryBean
FactoryBean是Spring提供给用户自定义Bean的工厂Bean,隐藏创建对象的细节。
FactoryBean中有三个方法:
// 用于返回Bean实例
T getObject() throws Exception;
// 返回Bean实例的class对象
Class<?> getObjectType();
// 返回当前Bean的作用域,默认单例
default boolean isSingleton() {
return true;
}
<bean id="userFactoryBean" class="com.xxx.factorybean.UserFactoryBean"/>
public class User {
public void hello() {
System.out.println("hello ...... ");
}
}
public class UserFactoryBean implements FactoryBean<User> {
@Override
public User getObject() throws Exception {
return new User();
}
@Override
public Class<?> getObjectType() {
return User.class;
}
}
```java
public static void main(String[] args) throws Exception {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
// 通过&可以在容器中取到FactoryBean本身的实例
UserFactoryBean userFactoryBean = (UserFactoryBean) applicationContext.getBean("&userFactoryBean");
User object = userFactoryBean.getObject();
object.hello();
// 这里调用getBean传入FactoryBean的名称返回的并不是FactoryBean本身,而是User
User user = (User) applicationContext.getBean("userFactoryBean");
user.hello();
}