最近在读DispatcherServlet 源代码,看到父级类org.springframework.web.servlet.HttpServletBean中关于BeanWrapper的一段代码, 继续追看下去,发现

BeanWrapper 是spring 底层核心的JavaBean包装接口, 默认实现类BeanWrapperImpl.所有bean的属性设置都是通过它来实现。

  1. @Override
  2. public final void init() throws ServletException {
  3. if (logger.isDebugEnabled()) {
  4. logger.debug("Initializing servlet '" + getServletName() + "'");
  5. }
  6. // Set bean properties from init parameters.
  7. try {
  8. PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
  9. BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
  10. ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
  11. bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
  12. initBeanWrapper(bw);
  13. bw.setPropertyValues(pvs, true);
  14. }
  15. catch (BeansException ex) {
  16. logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
  17. throw ex;
  18. }
  19. // Let subclasses do whatever initialization they like.
  20. initServletBean();
  21. if (logger.isDebugEnabled()) {
  22. logger.debug("Servlet '" + getServletName() + "' configured successfully");
  23. }

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory类 自动注入工厂抽象类

  1. @Override
  2. public Object configureBean(Object existingBean, String beanName) throws BeansException {
  3. markBeanAsCreated(beanName);
  4. BeanDefinition mbd = getMergedBeanDefinition(beanName);
  5. RootBeanDefinition bd = null;
  6. if (mbd instanceof RootBeanDefinition) {
  7. RootBeanDefinition rbd = (RootBeanDefinition) mbd;
  8. bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
  9. }
  10. if (!mbd.isPrototype()) {
  11. if (bd == null) {
  12. bd = new RootBeanDefinition(mbd);
  13. }
  14. bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
  15. bd.allowCaching = false;
  16. }
  17. <span style="color:#FF0000;"> BeanWrapper bw = new BeanWrapperImpl(existingBean);</span>
  18. initBeanWrapper(bw);
  19. populateBean(beanName, bd, bw);
  20. return initializeBean(beanName, existingBean, bd);
  21. }

BeanWrapperImpl 继承了属性编辑注册功能

如何设置值 :

  1. @Override
  2. public void setPropertyValue(String propertyName, Object value) throws BeansException {
  3. BeanWrapperImpl nestedBw;
  4. try {
  5. //获取嵌套的属性, like map[my.key], 没有嵌套属性就返回自己
  6. nestedBw = getBeanWrapperForPropertyPath(propertyName);
  7. }
  8. catch (NotReadablePropertyException ex) {
  9. throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
  10. "Nested property in path '" + propertyName + "' does not exist", ex);
  11. }
  12. PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName));
  13. nestedBw.setPropertyValue(tokens, new PropertyValue(propertyName, value));
  14. }

看下面具体方法的实现

  1. /**
  2. * Recursively navigate to return a BeanWrapper for the nested property path.
  3. * @param propertyPath property property path, which may be nested
  4. * @return a BeanWrapper for the target bean
  5. */
  6. protected BeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) {
  7. int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
  8. // Handle nested properties recursively.
  9. if (pos > -1) {
  10. String nestedProperty = propertyPath.substring(0, pos);
  11. String nestedPath = propertyPath.substring(pos + 1);
  12. //递归获取最后一个属性
  13. BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty);
  14. return nestedBw.getBeanWrapperForPropertyPath(nestedPath);
  15. }
  16. else {
  17. return this;
  18. }
  19. }

自己实现了个小例子:

  1. public class HelloWorld {
  2. private String msg = null;
  3. private Date date = null;
  4. public String getMsg() {
  5. return msg;
  6. }
  7. public void setMsg(String msg) {
  8. this.msg = msg;
  9. }
  10. public Date getDate() {
  11. return date;
  12. }
  13. public void setDate(Date date) {
  14. this.date = date;
  15. }
  16. }
  17. package com.sunkey.test;
  18. public class Pepole {
  19. private String name;
  20. private int sex;
  21. private HelloWorld helloWorld;
  22. public String getName() {
  23. return name;
  24. }
  25. public void setName(String name) {
  26. this.name = name;
  27. }
  28. public int getSex() {
  29. return sex;
  30. }
  31. public void setSex(int sex) {
  32. this.sex = sex;
  33. }
  34. public HelloWorld getHelloWorld() {
  35. return helloWorld;
  36. }
  37. public void setHelloWorld(HelloWorld helloWorld) {
  38. this.helloWorld = helloWorld;
  39. }
  40. }

测试代码:

    1. @Test
    2. public void testBeanWapper() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    3. Object obj = Class.forName("com.sunkey.test.HelloWorld").newInstance();
    4. BeanWrapper bw = new BeanWrapperImpl(obj);
    5. bw.setPropertyValue("msg", "HellowWorld");
    6. bw.setPropertyValue("date", new Date());
    7. System.out.println(bw.getPropertyValue("date") + "\n" + bw.getPropertyValue("msg"));
    8. }
    9. @Test
    10. public void testNestedBeanWapper() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    11. Object obj = Class.forName("com.sunkey.test.HelloWorld").newInstance();
    12. BeanWrapper bw = new BeanWrapperImpl(obj);
    13. bw.setPropertyValue("msg", "HellowWorld");
    14. bw.setPropertyValue("date", new Date());
    15. Object objP = Class.forName("com.sunkey.test.Pepole").newInstance();
    16. BeanWrapper pbw = new BeanWrapperImpl(objP);
    17. pbw.setPropertyValue("name", "jack");
    18. pbw.setPropertyValue("helloWorld", obj);
    19. System.out.println(pbw.getPropertyValue("name") + "\n" + pbw.getPropertyValue("helloWorld.msg"));
    20. pbw.setPropertyValue("helloWorld.msg", "HellowWorld修改过");
    21. System.out.println(pbw.getPropertyValue("name") + "\n" + pbw.getPropertyValue("helloWorld.msg")); }

Spring BeanWrapper分析的更多相关文章

  1. Spring研磨分析、Quartz任务调度、Hibernate深入浅出系列文章笔记汇总

    Spring研磨分析.Quartz任务调度.Hibernate深入浅出系列文章笔记汇总 置顶2017年04月27日 10:46:45 阅读数:1213 这系列文章主要是对Spring.Quartz.H ...

  2. MyBatis整合Spring原理分析

    目录 MyBatis整合Spring原理分析 MapperScan的秘密 简单总结 假如不结合Spring框架,我们使用MyBatis时的一个典型使用方式如下: public class UserDa ...

  3. 深入浅出Spring(四) Spring实例分析

    上次的博文中 深入浅出Spring(二) IoC详解 和 深入浅出Spring(三) AOP详解中,我们分别介绍了一下Spring框架的两个核心一个是IoC,一个是AOP.接下来我们来做一个Sprin ...

  4. 【spring源代码分析】--Bean的解析与注冊

    接着上一节继续分析,DefaultBeanDefinitionDocumentReader的parseBeanDefinitions方法: protected void parseBeanDefini ...

  5. Spring AOP分析(1) -- 基本概念

    AOP全称是Aspect Oriented Programming,面向切面编程,是面向对象编程(OOP:Object Oriented Programming)的补充和完善.一般在系统中,OOP利用 ...

  6. Spring AOP分析(2) -- JdkDynamicAopProxy实现AOP

    上文介绍了代理类是由默认AOP代理工厂DefaultAopProxyFactory中createAopProxy方法产生的.如果代理对象是接口类型,则生成JdkDynamicAopProxy代理:否则 ...

  7. Spring Aop分析

    前言 上文讲述ioc框架的实现,本文开始讲述aop.在spring中aop也有3种配置方式,注解形式的我们先不讨论.我们先看看xml形式的配置方式. <aop:config> <ao ...

  8. Spring IOC分析

    前言 关于Spring,我想无需做太多的解释了.每个Java程序猿应该都使用过他.Spring的ioc和aop极大的方便了我们的开发,但是Spring又有着不好的一面,为了符合开闭原则,Spring的 ...

  9. [置顶] 深入浅出Spring(四) Spring实例分析

    上次的博文中 深入浅出Spring(二) IoC详解 和 深入浅出Spring(三) AOP详解中,我们分别介绍了一下Spring框架的两个核心一个是IoC,一个是AOP.接下来我们来做一个Sprin ...

随机推荐

  1. 使用Android Support Design 控件TabLayout 方便快捷实现选项卡功能

    1.概述 TabLayout是在2015年的google大会上,google发布了新的Android Support Design库的新组件之一,以此来全面支持Material Design 设计风格 ...

  2. 一个 developer 的进化

    作为一名开发者已十年,回顾过往大概经历了这么几个阶段,如下图所示: Develop Code 作为刚走出学校的学生进入公司,在最初的 1-2 年内就处于该阶段. 不停的开发代码,为系统的大厦添砖加瓦, ...

  3. Android开发中的安全

    根据Android四大框架来解说安全机制 代码安全 java不同于C/C++,java是解释性语言,存在代码被反编译的隐患: 默认混淆器为proguard,最新版本为4.7: proguard还可用来 ...

  4. 安卓Eclipse开发者的福音

    我们知道,谷歌已经放弃对Eclipse(ADT)的维护更新了,现在官网上也找不到ADT的下载链接了,我们大多数同学仍在使用的ADT版本可能已经很老了,估计大多数的SDK版本只到4.4,而,在尝试升级以 ...

  5. Xcode自定义字体不能应用的原因

    想给UILabel换一个自定义的字体,从字体册选择兰亭黑: 然后选择 在Finder中显示,找到字体文件为Lantinghei.ttc: 将其拷贝到项目中,在info.plist里添加字体支持key, ...

  6. Objective-C的面向对象特性(一)

    Objective-C在c语言的基础上增加了面向对象特性,都有哪些面向对象特性呢? 其中第一个最重要的特性是类和对象的实现. Objective-C软件由许多对象构成,形成一个对象网络,对象之间通过发 ...

  7. 【Android 应用开发】Android 开发错误集锦

    1. eclipse的Device中不显示手机 在eclipse中连接不上手机,出现adb server didn't ACK  fail to start daemon 错误. 出现这种原因是因为a ...

  8. 【14】-java的单例设计模式详解

    预加载模式 代码: public class Singleton { private volatile static Singleton singleton = new Singleton(); pr ...

  9. leetcode之旅(8)-Contains Duplicate

    题目: Given an array of integers, find if the array contains any duplicates. Your function should retu ...

  10. javascript内置对象速查(二)

    Window对象 每个浏览器窗口或框架都对应于一个Window对象,它是随body或frameset元素的每个实例一起创建的对象. function status_text(){ window.sta ...