Spring BeanWrapper分析
最近在读DispatcherServlet 源代码,看到父级类org.springframework.web.servlet.HttpServletBean中关于BeanWrapper的一段代码, 继续追看下去,发现
BeanWrapper 是spring 底层核心的JavaBean包装接口, 默认实现类BeanWrapperImpl.所有bean的属性设置都是通过它来实现。
- @Override
- public final void init() throws ServletException {
- if (logger.isDebugEnabled()) {
- logger.debug("Initializing servlet '" + getServletName() + "'");
- }
- // Set bean properties from init parameters.
- try {
- PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
- BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
- ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
- bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
- initBeanWrapper(bw);
- bw.setPropertyValues(pvs, true);
- }
- catch (BeansException ex) {
- logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
- throw ex;
- }
- // Let subclasses do whatever initialization they like.
- initServletBean();
- if (logger.isDebugEnabled()) {
- logger.debug("Servlet '" + getServletName() + "' configured successfully");
- }
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory类 自动注入工厂抽象类
- @Override
- public Object configureBean(Object existingBean, String beanName) throws BeansException {
- markBeanAsCreated(beanName);
- BeanDefinition mbd = getMergedBeanDefinition(beanName);
- RootBeanDefinition bd = null;
- if (mbd instanceof RootBeanDefinition) {
- RootBeanDefinition rbd = (RootBeanDefinition) mbd;
- bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
- }
- if (!mbd.isPrototype()) {
- if (bd == null) {
- bd = new RootBeanDefinition(mbd);
- }
- bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
- bd.allowCaching = false;
- }
- <span style="color:#FF0000;"> BeanWrapper bw = new BeanWrapperImpl(existingBean);</span>
- initBeanWrapper(bw);
- populateBean(beanName, bd, bw);
- return initializeBean(beanName, existingBean, bd);
- }
BeanWrapperImpl 继承了属性编辑注册功能
如何设置值 :
- @Override
- public void setPropertyValue(String propertyName, Object value) throws BeansException {
- BeanWrapperImpl nestedBw;
- try {
- //获取嵌套的属性, like map[my.key], 没有嵌套属性就返回自己
- nestedBw = getBeanWrapperForPropertyPath(propertyName);
- }
- catch (NotReadablePropertyException ex) {
- throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
- "Nested property in path '" + propertyName + "' does not exist", ex);
- }
- PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName));
- nestedBw.setPropertyValue(tokens, new PropertyValue(propertyName, value));
- }
看下面具体方法的实现
- /**
- * Recursively navigate to return a BeanWrapper for the nested property path.
- * @param propertyPath property property path, which may be nested
- * @return a BeanWrapper for the target bean
- */
- protected BeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) {
- int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath);
- // Handle nested properties recursively.
- if (pos > -1) {
- String nestedProperty = propertyPath.substring(0, pos);
- String nestedPath = propertyPath.substring(pos + 1);
- //递归获取最后一个属性
- BeanWrapperImpl nestedBw = getNestedBeanWrapper(nestedProperty);
- return nestedBw.getBeanWrapperForPropertyPath(nestedPath);
- }
- else {
- return this;
- }
- }
自己实现了个小例子:
- public class HelloWorld {
- private String msg = null;
- private Date date = null;
- public String getMsg() {
- return msg;
- }
- public void setMsg(String msg) {
- this.msg = msg;
- }
- public Date getDate() {
- return date;
- }
- public void setDate(Date date) {
- this.date = date;
- }
- }
- package com.sunkey.test;
- public class Pepole {
- private String name;
- private int sex;
- private HelloWorld helloWorld;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getSex() {
- return sex;
- }
- public void setSex(int sex) {
- this.sex = sex;
- }
- public HelloWorld getHelloWorld() {
- return helloWorld;
- }
- public void setHelloWorld(HelloWorld helloWorld) {
- this.helloWorld = helloWorld;
- }
- }
测试代码:
- @Test
- public void testBeanWapper() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
- Object obj = Class.forName("com.sunkey.test.HelloWorld").newInstance();
- BeanWrapper bw = new BeanWrapperImpl(obj);
- bw.setPropertyValue("msg", "HellowWorld");
- bw.setPropertyValue("date", new Date());
- System.out.println(bw.getPropertyValue("date") + "\n" + bw.getPropertyValue("msg"));
- }
- @Test
- public void testNestedBeanWapper() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
- Object obj = Class.forName("com.sunkey.test.HelloWorld").newInstance();
- BeanWrapper bw = new BeanWrapperImpl(obj);
- bw.setPropertyValue("msg", "HellowWorld");
- bw.setPropertyValue("date", new Date());
- Object objP = Class.forName("com.sunkey.test.Pepole").newInstance();
- BeanWrapper pbw = new BeanWrapperImpl(objP);
- pbw.setPropertyValue("name", "jack");
- pbw.setPropertyValue("helloWorld", obj);
- System.out.println(pbw.getPropertyValue("name") + "\n" + pbw.getPropertyValue("helloWorld.msg"));
- pbw.setPropertyValue("helloWorld.msg", "HellowWorld修改过");
- System.out.println(pbw.getPropertyValue("name") + "\n" + pbw.getPropertyValue("helloWorld.msg")); }
Spring BeanWrapper分析的更多相关文章
- Spring研磨分析、Quartz任务调度、Hibernate深入浅出系列文章笔记汇总
Spring研磨分析.Quartz任务调度.Hibernate深入浅出系列文章笔记汇总 置顶2017年04月27日 10:46:45 阅读数:1213 这系列文章主要是对Spring.Quartz.H ...
- MyBatis整合Spring原理分析
目录 MyBatis整合Spring原理分析 MapperScan的秘密 简单总结 假如不结合Spring框架,我们使用MyBatis时的一个典型使用方式如下: public class UserDa ...
- 深入浅出Spring(四) Spring实例分析
上次的博文中 深入浅出Spring(二) IoC详解 和 深入浅出Spring(三) AOP详解中,我们分别介绍了一下Spring框架的两个核心一个是IoC,一个是AOP.接下来我们来做一个Sprin ...
- 【spring源代码分析】--Bean的解析与注冊
接着上一节继续分析,DefaultBeanDefinitionDocumentReader的parseBeanDefinitions方法: protected void parseBeanDefini ...
- Spring AOP分析(1) -- 基本概念
AOP全称是Aspect Oriented Programming,面向切面编程,是面向对象编程(OOP:Object Oriented Programming)的补充和完善.一般在系统中,OOP利用 ...
- Spring AOP分析(2) -- JdkDynamicAopProxy实现AOP
上文介绍了代理类是由默认AOP代理工厂DefaultAopProxyFactory中createAopProxy方法产生的.如果代理对象是接口类型,则生成JdkDynamicAopProxy代理:否则 ...
- Spring Aop分析
前言 上文讲述ioc框架的实现,本文开始讲述aop.在spring中aop也有3种配置方式,注解形式的我们先不讨论.我们先看看xml形式的配置方式. <aop:config> <ao ...
- Spring IOC分析
前言 关于Spring,我想无需做太多的解释了.每个Java程序猿应该都使用过他.Spring的ioc和aop极大的方便了我们的开发,但是Spring又有着不好的一面,为了符合开闭原则,Spring的 ...
- [置顶] 深入浅出Spring(四) Spring实例分析
上次的博文中 深入浅出Spring(二) IoC详解 和 深入浅出Spring(三) AOP详解中,我们分别介绍了一下Spring框架的两个核心一个是IoC,一个是AOP.接下来我们来做一个Sprin ...
随机推荐
- ARM-linux汇编常用语法
ARM linux常用汇编语法 ============================= 汇编语言每行的语法: lable: instruction ; comment 段操作: .section ...
- Leetcode_123_Best Time to Buy and Sell Stock III
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43740415 Say you have an array ...
- 新书《Ext JS 4.2 实战》终于出炉了
在清华大学出版社网站看到了书籍信息了,具体地址是:http://www.tup.tsinghua.edu.cn/book/Showbook.asp?CPBH=056140-01&DJ=51 预 ...
- 报表软件公司悬赏 BUG,100块钱1个的真实用意
上一篇文章我讲到,报表软件FineReport一反常态,做了个<提BUG,拿现金>的活动,1个BUG,100块钱.纵览软件行业,如金蝶用友浪潮IBM微软等国内外巨头,均没有这样的举动去征集 ...
- 队列链式存储 - 设计与实现 - API函数
队列相关基础内容参我的博文:队列顺序存储 - 设计与实现 - API函数 队列也是一种特殊的线性表:可以用线性表链式存储来模拟队列的链式存储. 主要代码: // linkqueue.h // 队列链式 ...
- Vim编译器的常用使用方法与技巧
vim操作 插入模式 命令行模式 末行模式 命令行模式 -> 插入模式 i ---> 在当前光标的前一个插入 I ---> 在行首插入 ...
- erlang在redhat上的安装
erlang在redhat上的安装 1) 下载源码包: http://www.erlang.org/download/otp_src_17.3.tar.gz 2) RHEL6.4预安装包 $ yum ...
- objective-c中的method swizz实现"猴打补丁"
ruby中的猴打补丁很好实现,下面给出例子: class String alias :org_upcase :upcase def upcase puts("trace me if you ...
- unix命令自我总结
三种参数类型 1⃣时间日期: cal times time 2⃣文字处理: ctl+v 输入控制字符 ${#str} str字符串长度 expr length $abc 同上 typeset -i x ...
- ubuntu14.04使用rails连接mysql数据库
rails自带的sqlite3各方面都不错,但是免费版缺少一个致命功能:加密码!虽说第三方有编译好的二进制版的加密版,但咱先不折腾鸟;直接上mysql吧. ubuntu安装mysql非常简单,先不聊; ...