重看Spring聚焦BeanFactory分析
BeanFactory是Spring框架的核心接口,它是工厂模式的实现,负责生产和管理bean对象。以下是BeanFactory的一个简单实现示例:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import java.util.HashMap;
import java.util.Map;
public class SimpleBeanFactory implements BeanFactory {
private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
private final Map<String, Object> singletonObjects = new HashMap<>();
public SimpleBeanFactory(String[] configLocations) {
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
for (String location : configLocations) {
reader.loadBeanDefinitions(location);
}
}
@Override
public Object getBean(String name) throws Exception {
return doGetBean(name);
}
@Override
public <T> T getBean(String name, Class<T> requiredType) throws Exception {
return (T) getBean(name);
}
@Override
public Object getBean(String name, Object... args) throws Exception {
return doGetBean(name);
}
@Override
public <T> T getBean(Class<T> requiredType) throws Exception {
return beanFactory.getBean(requiredType);
}
@Override
public <T> T getBean(Class<T> requiredType, Object... args) throws Exception {
return beanFactory.getBean(requiredType);
}
@Override
public boolean containsBean(String name) {
return beanFactory.containsBean(name);
}
@Override
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
return beanDefinition.isSingleton();
}
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
return beanDefinition.isPrototype();
}
@Override
评论已关闭