Spring populateBean属性赋值和自动注入

目录
  • 正文
  • 一、postProcessAfterInstantiation:修改Bean实例
  • 二、autowireByName:根据名称自动注入
  • 三、autowireByType:根据类型自动注入
  • 四、postProcessPropertyValues:处理属性值(@Resource、@Autowired、@Value)
  • 五、applyPropertyValues:填充属性
    • 5.1 解析依赖
    • 5.2 解析List

正文

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
   if (bw == null) {
      if (mbd.hasPropertyValues()) {
         throw new BeanCreationException(
               mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
      }
      else {
         // Skip property population phase for null instance.
         return;
      }
   }
   // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
   // state of the bean before properties are set. This can be used, for example,
   // to support styles of field injection.
   //一、修改Bean实例
   //给InstantiationAwareBeanPostProcessors最后一个机会在属性设置前改变bean
   // 具体通过调用ibp.postProcessAfterInstantiation方法,如果调用返回false,表示不必继续进行依赖注入,直接返回
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            //返回值为true则继续填充bean
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               return;
            }
         }
      }
   }
   PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
    // 根据bean的依赖注入方式:即是否标注有 @Autowired 注解或 autowire=“byType/byName” 的标签
   // 会遍历bean中的属性,根据类型或名称来完成相应的注入
   int resolvedAutowireMode = mbd.getResolvedAutowireMode();
   if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
      MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      // Add property values based on autowire by name if applicable.
      //二、根据名称自动注入
      if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
         autowireByName(beanName, mbd, bw, newPvs);
      }
      // Add property values based on autowire by type if applicable.
      //三、根据类型自动注入
      if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
         autowireByType(beanName, mbd, bw, newPvs);
      }
      pvs = newPvs;
   }
    // 容器是否注册了InstantiationAwareBeanPostProcessor
   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
   // 是否进行依赖检查
   boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
   PropertyDescriptor[] filteredPds = null;
   if (hasInstAwareBpps) {
      if (pvs == null) {
         pvs = mbd.getPropertyValues();
      }
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
            if (pvsToUse == null) {
               if (filteredPds == null) {
                  filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
               }
               //对所有需要依赖检查的属性进行后处理
               //四、处理属性值(@Autowired、@Value)
               pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
               if (pvsToUse == null) {
                  return;
               }
            }
            pvs = pvsToUse;
         }
      }
   }
   // 检查是否满足相关依赖关系,对应的depends-on属性,3.0后已弃用
   if (needsDepCheck) {
      if (filteredPds == null) {
         filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      }
      checkDependencies(beanName, mbd, filteredPds, pvs);
   }
   // 五、填充属性
   if (pvs != null) {
      applyPropertyValues(beanName, mbd, bw, pvs);
   }
}

一、postProcessAfterInstantiation:修改Bean实例

在填充属性之前调用postProcessAfterInstantiation修改Bean定义信息

if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
   for (BeanPostProcessor bp : getBeanPostProcessors()) {
      if (bp instanceof InstantiationAwareBeanPostProcessor) {
         InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
         if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
            return;
         }
      }
   }
}

二、autowireByName:根据名称自动注入

protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    //寻找bw中需要依赖注入的属性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        //检查缓存bean中是否存在当前bean
        if (containsBean(propertyName)) {
            //递归初始化相关的bean. 代码(1)
            Object bean = getBean(propertyName);
            pvs.add(propertyName, bean);
            //注册依赖
            registerDependentBean(propertyName, beanName);
            if (logger.isTraceEnabled()) {
                logger.trace("Added autowiring by name from bean name '" + beanName +
                        "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
            }
        } else {
            // 找不到则不处理
            if (logger.isTraceEnabled()) {
                logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
                        "' by name: no matching bean found");
            }
        }
    }
}

三、autowireByType:根据类型自动注入

protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
    // 获取自定义的类型转换器
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
    //寻找bw中需要依赖注入的属性
    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        try {
            // 获取属性描述符
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            //不要尝试按类型为Object类型自动装配:即使从技术上讲是不满意的,非简单的属性,也没有意义。
            if (Object.class != pd.getPropertyType()) {
                //探测指定属性的set方法
                MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
                // Do not allow eager init for type matching in case of a prioritized post-processor.
                boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
                DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
                //解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中,当属性存在多个封装bean时
                //比如: @Autowired private List<A> aList; 就会找到所有匹配A类型的bean并将其注入
                Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
                if (autowiredArgument != null) {
                    // 添加到待注入的bean列表中
                    pvs.add(propertyName, autowiredArgument);
                }
                for (String autowiredBeanName : autowiredBeanNames) {
                    //注册依赖
                    registerDependentBean(autowiredBeanName, beanName);
                    if (logger.isTraceEnabled()) {
                        logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
                                propertyName + "' to bean named '" + autowiredBeanName + "'");
                    }
                }
                autowiredBeanNames.clear();
            }
        } catch (BeansException ex) {
            throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
        }
    }
}

四、postProcessPropertyValues:处理属性值(@Resource、@Autowired、@Value)

CommonAnnotationBeanPostProcessor:处理@Resource

AutowiredAnnotationBeanPostProcessor:处理@Autowired、@Value。

详情:https://www.jb51.net/article/277330.htm

五、applyPropertyValues:填充属性

protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
    if (pvs.isEmpty()) {
        return;
    }
    if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
        ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
    }
    MutablePropertyValues mpvs = null;
    List<PropertyValue> original;
    if (pvs instanceof MutablePropertyValues) {
        mpvs = (MutablePropertyValues) pvs;
        //如果mpvs中的值已经被转换为对应的类型那么可以直接设置到beanWrapper
        if (mpvs.isConverted()) {
            // Shortcut: use the pre-converted values as-is.
            try {
                bw.setPropertyValues(mpvs);
                return;
            } catch (BeansException ex) {
                throw new BeanCreationException(
                        mbd.getResourceDescription(), beanName, "Error setting property values", ex);
            }
        }
        original = mpvs.getPropertyValueList();
    } else {
        //如果pvs并不是使用MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法
        original = Arrays.asList(pvs.getPropertyValues());
    }
    TypeConverter converter = getCustomTypeConverter();
    if (converter == null) {
        converter = bw;
    }
    //获取对应的解析器
    BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
    // Create a deep copy, resolving any references for values.
    List<PropertyValue> deepCopy = new ArrayList<>(original.size());
    boolean resolveNecessary = false;
    //遍历属性,将属性转换为对应属性的类型
    for (PropertyValue pv : original) {
        if (pv.isConverted()) {
            deepCopy.add(pv);
        } else {
            String propertyName = pv.getName();
            Object originalValue = pv.getValue();
            if (originalValue == AutowiredPropertyMarker.INSTANCE) {
                Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
                if (writeMethod == null) {
                    throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
                }
                originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
            }
            //解析、注入值
            Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
            Object convertedValue = resolvedValue;
            boolean convertible = bw.isWritableProperty(propertyName) &&
                    !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
            if (convertible) {
                convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
            }
            // Possibly store converted value in merged bean definition,
            // in order to avoid re-conversion for every created bean instance.
            if (resolvedValue == originalValue) {
                if (convertible) {
                    pv.setConvertedValue(convertedValue);
                }
                deepCopy.add(pv);
            } else if (convertible && originalValue instanceof TypedStringValue &&
                    !((TypedStringValue) originalValue).isDynamic() &&
                    !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
                pv.setConvertedValue(convertedValue);
                deepCopy.add(pv);
            } else {
                resolveNecessary = true;
                deepCopy.add(new PropertyValue(pv, convertedValue));
            }
        }
    }
    if (mpvs != null && !resolveNecessary) {
        mpvs.setConverted();
    }
    // Set our (possibly massaged) deep copy.
    try {
        bw.setPropertyValues(new MutablePropertyValues(deepCopy));
    } catch (BeansException ex) {
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Error setting property values", ex);
    }
}

解析、注入值

public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
    // We must check each value to see whether it requires a runtime reference
    // to another bean to be resolved.
    // 5.1 解析引用
    if (value instanceof RuntimeBeanReference) {
        RuntimeBeanReference ref = (RuntimeBeanReference) value;
        return resolveReference(argName, ref);
    }
    // 如果根据另一个Bean的name进行依赖,进入下面的分支
    else if (value instanceof RuntimeBeanNameReference) {
        String refName = ((RuntimeBeanNameReference) value).getBeanName();
        refName = String.valueOf(doEvaluate(refName));
        if (!this.beanFactory.containsBean(refName)) {
            throw new BeanDefinitionStoreException(
                    "Invalid bean name '" + refName + "' in bean reference for " + argName);
        }
        return refName;
    }
    // 解析BeanDefinitionHolder
    else if (value instanceof BeanDefinitionHolder) {
        // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
        BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
        return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
    }
    // 解析纯BeanDefinition
    else if (value instanceof BeanDefinition) {
        // Resolve plain BeanDefinition, without contained name: use dummy name.
        BeanDefinition bd = (BeanDefinition) value;
        String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
                ObjectUtils.getIdentityHexString(bd);
        return resolveInnerBean(argName, innerBeanName, bd);
    }
    // 解析数组
    else if (value instanceof ManagedArray) {
        // May need to resolve contained runtime references.
        ManagedArray array = (ManagedArray) value;
        Class<?> elementType = array.resolvedElementType;
        if (elementType == null) {
            String elementTypeName = array.getElementTypeName();
            if (StringUtils.hasText(elementTypeName)) {
                try {
                    elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
                    array.resolvedElementType = elementType;
                }
                catch (Throwable ex) {
                    // Improve the message by showing the context.
                    throw new BeanCreationException(
                            this.beanDefinition.getResourceDescription(), this.beanName,
                            "Error resolving array type for " + argName, ex);
                }
            }
            else {
                elementType = Object.class;
            }
        }
        return resolveManagedArray(argName, (List<?>) value, elementType);
    }
    //5.2解析List
    else if (value instanceof ManagedList) {
        // May need to resolve contained runtime references.
        return resolveManagedList(argName, (List<?>) value);
    }
    // 解析Set
    else if (value instanceof ManagedSet) {
        // May need to resolve contained runtime references.
        return resolveManagedSet(argName, (Set<?>) value);
    }
    // 解析Map
    else if (value instanceof ManagedMap) {
        // May need to resolve contained runtime references.
        return resolveManagedMap(argName, (Map<?, ?>) value);
    }
    // 解析Properties
    else if (value instanceof ManagedProperties) {
        Properties original = (Properties) value;
        Properties copy = new Properties();
        original.forEach((propKey, propValue) -> {
            if (propKey instanceof TypedStringValue) {
                propKey = evaluate((TypedStringValue) propKey);
            }
            if (propValue instanceof TypedStringValue) {
                propValue = evaluate((TypedStringValue) propValue);
            }
            if (propKey == null || propValue == null) {
                throw new BeanCreationException(
                        this.beanDefinition.getResourceDescription(), this.beanName,
                        "Error converting Properties key/value pair for " + argName + ": resolved to null");
            }
            copy.put(propKey, propValue);
        });
        return copy;
    }
    // 解析String
    else if (value instanceof TypedStringValue) {
        // Convert value to target type here.
        TypedStringValue typedStringValue = (TypedStringValue) value;
        Object valueObject = evaluate(typedStringValue);
        try {
            Class<?> resolvedTargetType = resolveTargetType(typedStringValue);
            if (resolvedTargetType != null) {
                return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
            }
            else {
                return valueObject;
            }
        }
        catch (Throwable ex) {
            // Improve the message by showing the context.
            throw new BeanCreationException(
                    this.beanDefinition.getResourceDescription(), this.beanName,
                    "Error converting typed String value for " + argName, ex);
        }
    }
    else if (value instanceof NullBean) {
        return null;
    }
    else {
        return evaluate(value);
    }
}

5.1 解析依赖

核心还是getBean方法!开始触发关联创建Bean

private Object resolveReference(Object argName, RuntimeBeanReference ref) {
    try {
        Object bean;
        // 获取BeanName
        String refName = ref.getBeanName();
        refName = String.valueOf(doEvaluate(refName));
        // 如果Bean在父容器,则去父容器取
        if (ref.isToParent()) {
            if (this.beanFactory.getParentBeanFactory() == null) {
                throw new BeanCreationException(
                        this.beanDefinition.getResourceDescription(), this.beanName,
                        "Can't resolve reference to bean '" + refName +
                                "' in parent factory: no parent factory available");
            }
            bean = this.beanFactory.getParentBeanFactory().getBean(refName);
        }
        else {
            // 在本容器,调用getBean
            bean = this.beanFactory.getBean(refName);
            this.beanFactory.registerDependentBean(refName, this.beanName);
        }
        if (bean instanceof NullBean) {
            bean = null;
        }
        return bean;
    }
    catch (BeansException ex) {
        throw new BeanCreationException(
                this.beanDefinition.getResourceDescription(), this.beanName,
                "Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
    }
}

5.2 解析List

直接把 List 集合塞入属性中即可。

private List<?> resolveManagedList(Object argName, List<?> ml) {
    List<Object> resolved = new ArrayList<>(ml.size());
    for (int i = 0; i < ml.size(); i++) {
        resolved.add(resolveValueIfNecessary(new KeyedArgName(argName, i), ml.get(i)));
    }
    return resolved;
}

以上就是Spring populateBean属性赋值和自动注入的详细内容,更多关于Spring populateBean属性的资料请关注我们其它相关文章!

(0)

相关推荐

  • springboot多数据源使用@Qualifier自动注入无效的解决

    目录 @Qualifier自动注入无效的解决 问题 问题的根本原因 其中问题出在 解决问题的方法 @Qualifier的作用和应用 @Qualifier的作用 @Qualifier自动注入无效的解决 问题 使用springboot进行多数据源时,发生了单例DataSource对应多个DataSourceBean的问题. 具体错误如下:XXXXX required a single bean, but 3 were found.通过@Qualifier来区分,或是在@Bean中添加name属性来区

  • 使用SpringBoot 工厂模式自动注入到Map

    目录 SpringBoot 工厂模式自动注入Map 一.建立工厂类 二.两个实现类 三.注入到map里,测试 SpringBoot自动注入原理 一.自动配置原理 二.细节 SpringBoot 工厂模式自动注入Map 一.建立工厂类 public interface AnimalFactory { String food(); String animal(); } 二.两个实现类 @Service public class Cat implements AnimalFactory { @Over

  • 解决springboot报错找不到自动注入的service问题

    springboot报错找不到自动注入的service 找了不少资料,最后发现是每个service接口(虽然已经使用了@service注解)的实现类都需要加上@service注解. 如果是使用junit生成的测试类,发现无法自动注入服务的话 在test启动类前加上 @RunWith(SpringRunner.class) @SpringBootTest @ComponentScan("com.XXX.service") 这是因为test包和启动类不在同一个包或子包下,无法自动注入 Sp

  • 如何通过一张图搞懂springBoot自动注入原理

    目录 @SpringBootApplication注解解读 1.@SpringBootConfiguration 2.@EnableAutoConfiguration @Inherited @AutoConfigurationPackage AutoConfigurationImportSelector.class 3.@ComponentScan 总结 @SpringBootApplication注解解读 为什么我们的启动类上标注一个@SpringBootApplication注解,再加一个r

  • Spring自动注入失败的解决方法

    Spring自动注入失败如何解决? 我有一个被Spring @Service注解的类(MileageFeeCalculator),它有一个用@Autowired注入的变量(rateService),但是当我用这个变量的时候,它显示为null.日志显示MileageFeeCalculator bean和MileageRateService bean都被创建了,但是当我调用service上的mileageCharge ()方法时,就会报NullPointerException错误.为什么Spring

  • springboot多模块化整合mybatis,mapper自动注入失败问题及解决

    目录 springboot多模块化整合mybatis,mapper自动注入失败 问题 解决 springboot mapper注入失败的一种原因 具体情况是 解决办法 springboot多模块化整合mybatis,mapper自动注入失败 问题 启动类添加@MapperScan或@ComponentScan,mapper类添加@Mapper或@Repository ==> Consider defining a bean of type 'com.ten.mapper.UserMapper'

  • Spring populateBean属性赋值和自动注入

    目录 正文 一.postProcessAfterInstantiation:修改Bean实例 二.autowireByName:根据名称自动注入 三.autowireByType:根据类型自动注入 四.postProcessPropertyValues:处理属性值(@Resource.@Autowired.@Value) 五.applyPropertyValues:填充属性 5.1 解析依赖 5.2 解析List 正文 protected void populateBean(String bea

  • spring级联属性赋值的两种方式解析

    这篇文章主要介绍了spring级联属性赋值的两种方式解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Car.java package com.gong.spring.beans; public class Car { private String name; public String getName() { return name; } public void setName(String name) { this.name = name

  • Spring@Value属性注入使用方法解析

    这篇文章主要介绍了Spring@Value属性注入使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在使用Spring框架的项目中,@Value是使用比较频繁的注解之一,它的作用是将配置文件中key对应的值赋值给它标注的属性.在日常使用中我们常用的功能都比较简单,本篇文章系统的带大家来了解一下@Value的使用方法. @Value注入支持形式 @Value属性注入功能根据注入的内容来源可分为两类:通过配置文件的属性注入和通过非配置文件

  • Spring自动装配之方法、构造器位置的自动注入操作

    Spring自动装配之方法.构造器位置的自动注入 1. 注解定义 @Autowired的定义信息如下: @Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Autowi

  • Spring Bean生命周期之属性赋值阶段详解

    目录 前言 属性自动装配 属性赋值前回调 属性的真正赋值 总结 前言 上节在谈论Bean的实例化过程时,在说明实例化后阶段时只是粗略地看了一下populateBean,并未展开分析.本节接着populateBean开始分析对象赋值阶段的事情. populateBean其实主要做了以下几件事: Bean实例化后回调,来决定是否进行属性赋值 (上节分析过了) 对属性进行自动装配 InstantiationAwareBeanPostProcessor属性赋值前回调 属性的真正赋值 protected

  • Spring加载属性文件方式(自动加载优先级问题)

    目录 Spring加载属性文件 方式1.用xml文件配置 方式2.用注解 对Spring加载顺序的理解 web.xml初始化 spring加载流程 Spring加载属性文件 方式1.用xml文件配置 正常情况下,spring整合mybatis的配置文件的dataSource部分如下  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"

  • Spring中属性注入详解

    本文演示了int.String.数组.list.set.map.Date等属性的注入. 其中Date类型的注入则是借助了Spring提供的属性编辑器来实现的,首先是用到的五个实体类 package com.jadyer.model; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; /** * 常见属性的注入 * @see 包括int,String,Array,lis

  • 你所不知道的Spring自动注入详解

    自动注入和@Autowire @Autowire不属于自动注入! 注入方式(重要) 在Spring官网上(文档),定义了在Spring中的注入方式一共有两种:set方法和构造函数. 也就是说,你想在A类里面注入另外一个B类,无论你是通过写 XML文件,或者通过 @Autowried,他们最终都是通过这个A类的set方法或者构造函数,将B类注入到A类中! 换句话说,你如果A类里面没有setB(B b){-},那你就别想通过set方法把B类注入到A类中 自动注入 首先摆出一个比较颠覆的观点:@Aut

  • 详解Spring注解驱动开发之属性赋值

    一.@Value注解 在Person的属性上使用@Value注解指定注入值 public class Person { @Value("#{20-2}") //SpEL表达式 #{} private Integer id; @Value("张三") //基本数据类型 private String name; } 配置类 @Configuration public class MainConfigOfPropertyValues { @Bean public Pers

  • Spring中如何使用@Value注解实现给Bean属性赋值

    目录 属性赋值 @Value注解的定义: 测试 1.在添加了Spring依赖的Maven项目中创建 2.在resources目录下创建一个配置文件person.properties 3.创建配置类 4.创建测试类进行测试 5.测试结果: 如何给Bean的属性赋值(注入) 1.通过构造方法设置值. 2.设置注入(通过set方法) 属性赋值 只用Spring注解开发的时候,可以使用@Value搭配@PropertySource注解进行给Bean的属性进行赋值. @Value @Value注解的定义:

随机推荐