Spring使用回顾
数据访问层 定义三层架构和xml配置
public interface UserDao {
public void add();
}
public class UserDaoImpl implements UserDao {
public void add() {
System.out.println("userDaoImpl ....");
}
}
public interface UserService {
public void add();
}
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void add() {
System.out.println("userServiceImpl ...");
userDao.add();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
</beans>
/**
* spring-context-support 模块是Spring Ioc容器以及Ioc子容器的扩展支持
* spring-context-indexer 模块是Spring的类管理组件和Classpath扫描组件
*
* spring-expression模块是统一表达式语言(EL)的扩展模块可以查询管理运行中的对象 同时也可以方便的调用对象方法 以及操作数组集合等 他的语法类似传统EL 但提供了额外的功能 最出色的就是函数调用和简单的字符串模版函数
* EL的特性是基于Spring产品的需求而设计的 可以非常方便的同Spring Ioc进行交互
*/
public class UserController {
public static void main(String[] args) {
/**
* 立即加载 扩展了BeanFactory接口,提供了更多的功能
*/
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
/**
* 延迟加载 使用到了的时候才会创建
*/
BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
UserService userService1 = beanFactory.getBean("userService", UserService.class);
userService1.add();
}
通过上面代码及结果可以看出:
1.userService对象是从applicationContext容器对象获取到的,也就是userService对象交由spring进行管理。
2.上面结果可以看到调用了UserDao对象中的add方法,也就是说UserDao子实现类对象也交由spring管理了。
3.UserService中的userDao变量我们并没有进行赋值,但是可以正常使用,说明spring已经将UserDao对象赋值给了userDao变量。
上面三点体现了Spring框架的IOC(Inversion of Control)和DI(Dependency Injection, DI)
Spring IOC相关接口类图
其中,BeanFactory作为最顶层的一个接口,定义了IoC容器的基本功能规范,BeanFactory有三个重要的子接口:ListableBeanFactory HierarchicalBeanFactory AutowireCapableBeanFactory 但是从类图中我们可以发现最终的默认实现类是DefaultListableBeanFactory 它实现了所有的接口。
每个接口都有它的使用场合,主要是为了区分在Spring内部操作过程中对象的传递和转化,对对象的数据访问所做的限制。例如:
1.ListableBeanFactory 接口表示这些Bean可列表化。
2.HierarchicalBeanFactory 表示这些Bean 是有继承关系的,也就是每个 Bean 可能有父 Bean
3.AutowireCapableBeanFactory 接口定义Bean的自动装配规则。
最基本的IoC容器接口是BeanFactory
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
//根据bean的名称获取IOC容器中的的bean对象
Object getBean(String name) throws BeansException;
//根据bean的名称获取IOC容器中的的bean对象,并指定获取到的bean对象的类型,这样我们使用时就不需要进行类型强转了
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
Object getBean(String name, Object... args) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);
<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);
//判断容器中是否包含指定名称的bean对象
boolean containsBean(String name);
//根据bean的名称判断是否是单例
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;
@Nullable
Class<?> getType(String name) throws NoSuchBeanDefinitionException;
String[] getAliases(String name);
}
在BeanFactory里只对IoC容器的基本行为做了定义,根本不关心你的Bean是如何定义及怎样加载的。正如我们只关心能从工厂里得到什么产品,不关心工厂是怎么生产这些产品的。
BeanFactory有一个很重要的子接口 就是ApplicationContext接口,该接口主要来规范容器中的bean对象是非延时加载,即在创建容器对象的时候就对象bean进行初始化 并存储到一个容器中。
要知道工厂是如何产生对象的,我们需要看具体的IoC容器实现,Spring提供了许多IoC容器实现,比如:
1.ClasspathXmlApplicationContext : 根据类路径加载xml配置文件,并创建IOC容器对象。
2.FileSystemXmlApplicationContext :根据系统路径加载xml配置文件,并创建IOC容器对象。
3.AnnotationConfigApplicationContext :加载注解类配置,并创建IOC容器。
BeanDefinition解析
Spring IoC容器管理我们定义的各种Bean对象及其相互关系,而Bean对象在Spring实现中是以BeanDefinition来描述的,如下面配置文件
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
bean标签还有很多属性:
scope、init-method、destory-method等。
BeanDefinitionReader解析
Bean的解析过程非常复杂,功能被分得很细,因为这里需要被扩展的地方很多,必须保证足够的灵活性,以应对可能的变化。Bean的解析主要就是对Spring配置文件的解析。这个解析过程主要通过BeanDefinitionReader来完成,看看Spring中BeanDefinitionReader的类结构图,如下图示。
BeanDefinitionReader接口定义的功能来理解它具体的作用:
public interface BeanDefinitionReader {
//获取BeanDefinitionRegistry注册器对象
BeanDefinitionRegistry getRegistry();
@Nullable
ResourceLoader getResourceLoader();
@Nullable
ClassLoader getBeanClassLoader();
BeanNameGenerator getBeanNameGenerator();
/*
下面的loadBeanDefinitions都是加载bean定义,从指定的资源中
*/
int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException;
int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException;
int loadBeanDefinitions(String location) throws BeanDefinitionStoreException;
int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException;
}
BeanDefinitionRegistry解析
BeanDefinitionReader用来解析bean定义,并封装BeanDefinition对象,而我们定义的配置文件中定义了很多bean标签,所以就有一个问题,解析的BeanDefinition对象存储到哪儿?答案就是BeanDefinition的注册中心,而该注册中心顶层接口就是BeanDefinitionRegistry。
BeanDefinitionRegistry接口定义的功能来理解它具体的作用:
public interface BeanDefinitionRegistry extends AliasRegistry {
//往注册表中注册bean
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException;
//从注册表中删除指定名称的bean
void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
//获取注册表中指定名称的bean
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
//判断注册表中是否已经注册了指定名称的bean
boolean containsBeanDefinition(String beanName);
//获取注册表中所有的bean的名称
String[] getBeanDefinitionNames();
int getBeanDefinitionCount();
boolean isBeanNameInUse(String beanName);
}
创建容器
ClassPathXmlApplicationContext对Bean配置资源的载入是从refresh()方法开始的。refres()方法是一个模板方法,规定了 IoC 容器的启动流程,有些逻辑要交给其子类实现。它对 Bean 配置资源进行载入,ClassPathXmlApplicationContext通过调用其父类AbstractApplicationContext的refresh()方法启动整个IoC容器对Bean定义的载入过程。
开始自定义IOC
现要对下面的配置文件进行解析,并自定义Spring框架的IOC对涉及到的对象进行管理。
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="userService" class="com.itheima.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"></bean>
</beans>
PropertyValue类
/**
* @author Vincent.wang
* @description 封装bean标签下面的property标签的信息
* name:属性名 ref:属性值 value:属性值:给基本数据类型以及String类型的属性赋值
* @date 2024/2/15 21:30
*/
public class PropertyValue {
private String name;
private String ref;
private String value;
public PropertyValue() {
}
public PropertyValue(String name, String ref,String value) {
this.name = name;
this.ref = ref;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
MutablePropertyValues类
一个bean标签可以有多个property子标签,所以再定义一个MutablePropertyValues类,用来存储并管理多个PropertyValue对象。
/**
* @author Vincent.wang
* @description 用户储存和管理多个PropertyValue对象
* @date 2024/2/15 21:33
*/
public class MutablePropertyValues implements Iterable<PropertyValue> {
private final List<PropertyValue> propertyValueList;
public MutablePropertyValues() {
this.propertyValueList = new ArrayList<PropertyValue>();
}
public MutablePropertyValues(List<PropertyValue> propertyValueList) {
this.propertyValueList = (propertyValueList != null ? propertyValueList : new ArrayList<PropertyValue>());
}
public PropertyValue[] getPropertyValues() {
return this.propertyValueList.toArray(new PropertyValue[0]);
}
public PropertyValue getPropertyValue(String propertyName) {
for (PropertyValue pv : this.propertyValueList) {
if (pv.getName().equals(propertyName)) {
return pv;
}
}
return null;
}
@Override
public Iterator<PropertyValue> iterator() {
return propertyValueList.iterator();
}
public boolean isEmpty() {
return this.propertyValueList.isEmpty();
}
public MutablePropertyValues addPropertyValue(PropertyValue pv) {
for (int i = 0; i < this.propertyValueList.size(); i++) {
PropertyValue currentPv = this.propertyValueList.get(i);
if (currentPv.getName().equals(pv.getName())) {
this.propertyValueList.set(i, new PropertyValue(pv.getName(),pv.getRef(), pv.getValue()));
return this;
}
}
this.propertyValueList.add(pv);
return this;
}
public boolean contains(String propertyName) {
return getPropertyValue(propertyName) != null;
}
}
BeanDefinition类
BeanDefinition类用来封装bean信息的,主要包含id(即bean对象的名称)、class(需要交由spring管理的类的全类名)及子标签property数据。
/**
* @author Vincent.wang
* @description 用来封装bean标签数据
* @date 2024/2/15 21:49
*/
public class BeanDefinition {
private String id;
private String className;
private MutablePropertyValues propertyValues;
public BeanDefinition() {
propertyValues = new MutablePropertyValues();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public void setPropertyValues(MutablePropertyValues propertyValues) {
this.propertyValues = propertyValues;
}
public MutablePropertyValues getPropertyValues() {
return propertyValues;
}
}
定义注册表相关类
BeanDefinitionRegistry接口定义了注册表的相关操作,定义如下功能:
1.注册BeanDefinition对象到注册表中
2.从注册表中删除指定名称的BeanDefinition对象
3.根据名称从注册表中获取BeanDefinition对象
4.判断注册表中是否包含指定名称的BeanDefinition对象
5.获取注册表中BeanDefinition对象的个数
6.获取注册表中所有的BeanDefinition的名称
public interface BeanDefinitionRegistry {
//注册BeanDefinition对象到注册表中
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition);
//从注册表中删除指定名称的BeanDefinition对象
void removeBeanDefinition(String beanName) throws Exception;
//根据名称从注册表中获取BeanDefinition对象
BeanDefinition getBeanDefinition(String beanName) throws Exception;
boolean containsBeanDefinition(String beanName);
int getBeanDefinitionCount();
String[] getBeanDefinitionNames();
}
SimpleBeanDefinitionRegistry类
该类实现了BeanDefinitionRegistry接口,定义了Map集合作为注册表容器。
public class SimpleBeanDefinitionRegistry implements BeanDefinitionRegistry {
private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<String, BeanDefinition>();
@Override
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
beanDefinitionMap.put(beanName,beanDefinition);
}
@Override
public void removeBeanDefinition(String beanName) throws Exception {
beanDefinitionMap.remove(beanName);
}
@Override
public BeanDefinition getBeanDefinition(String beanName) throws Exception {
return beanDefinitionMap.get(beanName);
}
@Override
public boolean containsBeanDefinition(String beanName) {
return beanDefinitionMap.containsKey(beanName);
}
@Override
public int getBeanDefinitionCount() {
return beanDefinitionMap.size();
}
@Override
public String[] getBeanDefinitionNames() {
return beanDefinitionMap.keySet().toArray(new String[1]);
}
}
定义解析器相关类
BeanDefinitionReader是用来解析配置文件并在注册表中注册bean的信息。定义了两个规范:
1.获取注册表的功能,让外界可以通过该对象获取注册表对象。
2.加载配置文件,并注册bean数据。
public interface BeanDefinitionReader {
//获取注册表对象
BeanDefinitionRegistry getRegistry();
//加载配置文件并在注册表中进行注册
void loadBeanDefinitions(String configLocation) throws Exception;
}
XmlBeanDefinitionReader类
XmlBeanDefinitionReader类是专门用来解析xml配置文件的。该类实现BeanDefinitionReader接口并实现接口中的两个功能。
public class XmlBeanDefinitionReader implements BeanDefinitionReader {
private BeanDefinitionRegistry registry;
public XmlBeanDefinitionReader() {
this.registry = new SimpleBeanDefinitionRegistry();
}
@Override
public BeanDefinitionRegistry getRegistry() {
return registry;
}
@Override
public void loadBeanDefinitions(String configLocation) throws Exception {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(configLocation);
SAXReader reader = new SAXReader();
Document document = reader.read(is);
Element rootElement = document.getRootElement();
//解析bean标签
parseBean(rootElement);
}
private void parseBean(Element rootElement) {
List<Element> elements = rootElement.elements();
for (Element element : elements) {
String id = element.attributeValue("id");
String className = element.attributeValue("class");
//将id属性和class属性封装为BeanDefinition
BeanDefinition beanDefinition = new BeanDefinition();
beanDefinition.setId(id);
beanDefinition.setClassName(className);
List<Element> list = element.elements("property");
MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
for (Element element1 : list) {
//封装property标签对象
String name = element1.attributeValue("name");
String ref = element1.attributeValue("ref");
String value = element1.attributeValue("value");
PropertyValue propertyValue = new PropertyValue(name,ref,value);
mutablePropertyValues.addPropertyValue(propertyValue);
}
beanDefinition.setPropertyValues(mutablePropertyValues);
registry.registerBeanDefinition(id,beanDefinition);
}
}
}
IOC容器相关类
BeanFactory接口
在该接口中定义IOC容器的统一规范即获取bean对象。
public interface BeanFactory {
//根据bean对象的名称获取bean对象
Object getBean(String name) throws Exception;
//根据bean对象的名称获取bean对象,并进行类型转换
<T> T getBean(String name, Class<? extends T> clazz) throws Exception;
}
ApplicationContext类
该接口的所以的子实现类对bean对象的创建都是非延时的,所以在该接口中定义 refresh()
方法,该方法主要完成以下两个功能:
1.加载配置文件。
2.根据注册表中的BeanDefinition对象封装的数据进行bean对象的创建。
public interface ApplicationContext extends BeanFactory {
//进行配置文件加载并进行对象创建
void refresh() throws IllegalStateException, Exception;
}
AbstractApplicationContext类
1.作为ApplicationContext接口的子类,所以该类也是非延时加载,所以需要在该类中定义一个Map集合,作为bean对象存储的容器。
2.声明BeanDefinitionReader类型的变量,用来进行xml配置文件的解析,符合单一职责原则。
BeanDefinitionReader类型的对象创建交由子类实现,因为只有子类明确到底创建BeanDefinitionReader哪儿个子实现类对象。
public abstract class AbstractApplicationContext implements ApplicationContext {
protected BeanDefinitionReader beanDefinitionReader;
//用来存储bean对象的容器 key存储的是bean的id值,value存储的是bean对象
protected Map<String, Object> singletonObjects = new HashMap<String, Object>();
//存储配置文件的路径
protected String configLocation;
public void refresh() throws IllegalStateException, Exception {
//加载BeanDefinition
beanDefinitionReader.loadBeanDefinitions(configLocation);
//初始化bean
finishBeanInitialization();
}
//bean的初始化
//该类finishBeanInitialization()方法中调用getBean()方法使用到了模板方法模式。
private void finishBeanInitialization() throws Exception {
BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
String[] beanNames = registry.getBeanDefinitionNames();
for (String beanName : beanNames) {
BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
getBean(beanName);
}
}
}
ClassPathXmlApplicationContext类
该类主要是加载类路径下的配置文件,并进行bean对象的创建,主要完成以下功能:
1.在构造方法中,创建BeanDefinitionReader对象。
2.在构造方法中,调用refresh()方法,用于进行配置文件加载、创建bean对象并存储到容器中。
3.重写父接口中的getBean()方法,并实现依赖注入操作。
public class ClassPathXmlApplicationContext extends AbstractApplicationContext{
public ClassPathXmlApplicationContext(String configLocation) {
this.configLocation = configLocation;
//构建XmlBeanDefinitionReader对象
beanDefinitionReader = new XmlBeanDefinitionReader();
try {
this.refresh();
} catch (Exception e) {
}
}
//根据bean的id属性值获取bean对象
@Override
public Object getBean(String name) throws Exception {
//return singletonObjects.get(name);
Object obj = singletonObjects.get(name);
if(obj != null) {
return obj;
}
BeanDefinitionRegistry registry = beanDefinitionReader.getRegistry();
BeanDefinition beanDefinition = registry.getBeanDefinition(name);
if(beanDefinition == null) {
return null;
}
String className = beanDefinition.getClassName();
Class<?> clazz = Class.forName(className);
Object beanObj = clazz.newInstance();
MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
for (PropertyValue propertyValue : propertyValues) {
String propertyName = propertyValue.getName();
String value = propertyValue.getValue();
String ref = propertyValue.getRef();
if(ref != null && !"".equals(ref)) {
Object bean = getBean(ref);
String methodName = StringUtils.getSetterMethodNameByFieldName(propertyName);
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if(method.getName().equals(methodName)) {
method.invoke(beanObj,bean);
}
}
}
if(value != null && !"".equals(value)) {
String methodName = StringUtils.getSetterMethodNameByFieldName(propertyName);
Method method = clazz.getMethod(methodName, String.class);
method.invoke(beanObj,value);
}
}
singletonObjects.put(name,beanObj);
return beanObj;
}
@Override
public <T> T getBean(String name, Class<? extends T> clazz) throws Exception {
Object bean = getBean(name);
if(bean != null) {
return clazz.cast(bean);
}
return null;
}
}
自定义Spring IOC总结
使用到的设计模式
1.工厂模式。这个使用工厂模式 + 配置文件的方式。
2.单例模式。Spring IOC管理的bean对象都是单例的,此处的单例不是通过构造器进行单例的控制的,而是spring框架对每一个bean只创建了一个对象。
3.模板方法模式。AbstractApplicationContext类中的finishBeanInitialization()方法调用了子类的 getBean()方法,因为getBean()的实现和环境息息相关。
4.迭代器模式。对于MutablePropertyValues类定义使用到了迭代器模式,因为此类存储并管理 PropertyValue对象,也属于一个容器,所以给该容器提供一个遍历方式。