在类中的定义的属性我们可以通过Spring的容器给他们赋值,Spring这种功能在我们实际中有什么作用呢?举个我在工作中实际用的例子吧,
如果我们把数据库的连接配置文件加密了,我们就不能直接加载使用了,这时候我们需要先把配置文件进行解密,然后把解密之后的值赋给一个常量类,这时候我们通过加载这个常量类中的属性来完成数据库的连接。
代码如下:

    <!-- 解密config.properties文件 --><bean id="myPropertyConfigurer"  class="com.fyw.commons.security.DecryptPropertyPlaceholderConfigurer">         <property name="locations" value="classpath:config.properties"/>             <!--<list><value>classpath:config.properties</value></list>       </property>      -->  <property name="fileEncoding" value="UTF-8"/>         <property name="keyLocation" value="classpath:key.key" />   </bean><!-- 常量属性--><bean id="Constant" class="com.fyw.common.Constant"><property name="DEFAULT_SAVE_PATH" value="${file.defaultSavePath}" /><property name="COMPARE_ACCOUNT_FILE_PATH" value="${file.compareAccountFilePath}" /><property name="SHARE_PROFITS_FILE_PATH" value="${file.shareProfitsFilePath}" /><property name="ENDECRYPT_PUBLIC_KEY" value="${file.publicKey}" /><property name="EMAIL_FROM" value="${email.from}" /><property name="EMAIL_TO_ERROR" value="${email.to.error}" /><property name="EMAIL_TO_NORMAL" value="${email.to.normal}" /><property name="ENV" value="${env}" /></bean>

下面看看DecryptPropertyPlaceholderConfigurer

public class DecryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {private Resource[] locations;         private Resource keyLocation;     private String fileEncoding; public void setLocations(Resource[] locations){ try {this.locations = locations;  } catch (Exception e) {e.printStackTrace();}} public void setKeyLocation(Resource keyLocation){ try {this.keyLocation = keyLocation;   } catch (Exception e) {e.printStackTrace();}}       public void setFileEncoding(String fileEncoding) {this.fileEncoding = fileEncoding;}public void loadProperties(Properties props) throws IOException{ if (this.locations != null){            PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();             for (int i = 0; i < this.locations.length; i++)             {                 Resource location = this.locations[i];                 if (logger.isInfoEnabled()){                     logger.info("Loading properties file from " + location);                }                 InputStream is = null;                 try{                     is = location.getInputStream();                     Key key =getKey(keyLocation.getInputStream());                   is =doDecrypt(key, is);                     if (fileEncoding != null){                        propertiesPersister.load(props, new InputStreamReader(                               is, fileEncoding));                    }else{                         propertiesPersister.load(props, is);                    } }             finally{                   if (is != null){                        is.close();                    }                }          }         }    } /**      * <ul>     * <li>Description:[根据流得到密钥]</li>         * <li>Midified by [修改人] [修改时间]</li>          */    public static Key getKey(InputStream is){         try{             ObjectInputStream ois = new ObjectInputStream(is);    return (Key) ois.readObject();         }catch (Exception e){          e.printStackTrace();             throw new RuntimeException(e);        }     } /**      * <ul>     * <li>Description:[对数据进行解密]</li>         * </ul>          * @param key      * @param in     * @return    */   public static InputStream doDecrypt(Key key, InputStream in){         try{       Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");         cipher.init(Cipher.DECRYPT_MODE, key);       ByteArrayOutputStream bout = new ByteArrayOutputStream();       byte[] tmpbuf = new byte[1024];         int count = 0;        while ((count = in.read(tmpbuf)) != -1){                   bout.write(tmpbuf, 0, count);            tmpbuf = new byte[1024];       }         in.close();         byte[] orgData = bout.toByteArray();         byte[] raw = cipher.doFinal(orgData);         ByteArrayInputStream bin = new ByteArrayInputStream(raw);        return bin;    }catch (Exception e){          e.printStackTrace();        throw new RuntimeException(e); }     }
}

完成以上操作我们就可以直接使用Constant类中的常量了。
以上是对普通的字段通过SpringIOC进行装配,如果是其他类型的呢?下面我说说Set、List、Map、Properties这几种类型的赋值方法:
配置文件如下:

<bean id="personService" class="com.fyw.service.impl.PersonServiceBean"><property name="sets"><set><value>第一个</value><value>第二个</value><value>第三个</value></set></property><property name="lists"><list><value>第一个list元素</value><value>第二个list元素</value><value>第三个list元素</value></list></property><property name="properties"><props><prop key="key1">value1</prop><prop key="key2">value2</prop><prop key="key3">value3</prop></props></property><property name="maps"><map><entry key="key-1" value="value-1"/><entry key="key-2" value="value-2"/><entry key="key-3" value="value-3"/></map></property></bean>

PersonService类的代码很简单,如下:

public class PersonServiceBean implements PersonService {private Set<String> sets = new HashSet<String>();private List<String> lists = new ArrayList<String>();private Properties properties = new Properties();private Map<String, String> maps = new HashMap<String, String>();public Map<String, String> getMaps() {return maps;}public void setMaps(Map<String, String> maps) {this.maps = maps;}public Properties getProperties() {return properties;}public void setProperties(Properties properties) {this.properties = properties;}public Set<String> getSets() {return sets;}public void setSets(Set<String> sets) {this.sets = sets;}public List<String> getLists() {return lists;}public void setLists(List<String> lists) {this.lists = lists;}public void save(){}
}

测试代码如下:

@Test public void instanceSpring(){AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");PersonService personService = (PersonService)ctx.getBean("personService");System.out.println("========set===========");for(String value : personService.getSets()){System.out.println(value);}System.out.println("========list===========");for(String value : personService.getLists()){System.out.println(value);}System.out.println("========properties===========");for(Object key : personService.getProperties().keySet()){System.out.println(key+"="+ personService.getProperties().getProperty((String)key));}System.out.println("========map===========");for(String key : personService.getMaps().keySet()){System.out.println(key+"="+ personService.getMaps().get(key));}ctx.close();}

Spring学习笔记——Spring如何装配各种类型的属性以及实际应用相关推荐

  1. Spring学习笔记--spring+mybatis集成

    前言: 技术的发展, 真的是日新月异. 作为javaer, 都不约而同地抛弃裸写jdbc代码, 而用各种持久化框架. 从hibernate, Spring的JDBCTemplate, 到ibatis, ...

  2. Spring学习笔记之MyBatis

    系列文章目录 Spring学习笔记 之 Springhttps://blog.csdn.net/weixin_43985478/article/details/124411746?spm=1001.2 ...

  3. JavaEE——Spring学习笔记01【Ioc开发的模式】

    JavaEE--Spring学习笔记01[Ioc开发的模式] JavaEE--Spring学习笔记02[Spring和Mybatis的整合] JavaEE--Spring学习笔记03[AOP开发] J ...

  4. spring学习笔记03-spring-DI-依赖注入详解(通过xml配置文件来配置依赖注入)

    spring学习笔记03-spring-DI-依赖注入详解 1.概念 2.构造函数注入 3.set方法注入 4.集合的注入 需要被注入的实体对象 package com.itheima.service ...

  5. Spring学习笔记:配置单数据源

    Spring学习笔记:配置单数据源 一.Spring Boot默认数据源类型 Springboot默认支持4种数据源类型,定义在 org.springframework.boot.autoconfig ...

  6. 【Spring学习笔记 九】Spring声明式事务管理实现机制

    什么是事务?事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用,关乎数据准确性的地方我们一定要用到事务,防止业务逻辑出错. 什么是事务管理,事务管理对于企业应用而言至 ...

  7. spring学习笔记(一)创建对象的四种方式

    spring学习笔记(一)创建对象的四种方式 一.简介 ​ Spring是一个轻量级控制反转(IoC)和面向切面(AOP)的容器框架. ​ 所谓IoC就是Iversion of Control,控制反 ...

  8. JavaEE——Spring学习笔记03【AOP开发】

    JavaEE--Spring学习笔记01[Ioc开发的模式] JavaEE--Spring学习笔记02[Spring和Mybatis的整合] JavaEE--Spring学习笔记03[AOP开发] J ...

  9. CHY的Spring学习笔记---师从动力节点王鹤老师(B站白嫖)

    Spring学习笔记 核心技术:ioc和aop ioc:使用di(依赖注入)实现控制反转,底层使用的是反射机制 spring可以创建自己写的类的对象,也可以创建非自定义对象,只要知道类的全限定名即可. ...

最新文章

  1. python简单代码加法-CPython 源码中整数加法的实现
  2. 10款jQuery/CSS3动画应用 超有用
  3. 9000+ 字,彻底征服 Spring AOP ,美滋滋
  4. 完美解决Ubuntu16.04虚拟机窗口自适应问题
  5. 《独家记忆》见面会高甜宠粉 张超现场解锁隐藏技能
  6. rgb红色范围_【论文阅读18】RGB-D Object-Oriented Semantic Mapping
  7. 【蓝桥杯单片机】矩阵键盘和独立键盘新解(更稳定更高复用性)
  8. mysql 存储过程 大于等于_mysql 存储过程 大于
  9. IT十八掌徐培成第二天笔记
  10. 最大公约数是啥意思_要求最大公约数是什么含义(如何求最大公约数)
  11. Cosy主题3.0使用教程
  12. 带你玩转Jetson Xavier NX系列教程 | Xavier NX刷机教程
  13. HTTP(超文本传输协议)详细解析
  14. word中装订线位置_word装订线位置在哪里
  15. 【论文笔记】知识图谱推理PRA——Relational retrieval using a combination of path-constrained random walks
  16. IDEA常用快捷键(Windows)
  17. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree
  18. 《中国脱发地图》来袭!最秃的省是?
  19. eNSP(华为模拟器)基本配置命令
  20. CentOS7 Hadoop 2.7.3 Hive 2.1.1

热门文章

  1. 【无标题】KAS 新途径ASIC最新款Superscalar K10优劣势
  2. linux openmpi 位置,ubuntu下安装openMPI
  3. 微信小程序一次获取多个formid插件,实现主动推送多次消息
  4. 产品周报第28期|CSDN编辑器升级,新增插入已有视频功能
  5. spring总结2——SpringIOC以及DI
  6. 游戏UI资源优化(一) COCOS2D-X里如何用TEXTUREPACKER和像素格式来优化SPRITESHEET
  7. MacOS 开启 2k 屏幕的 HiDPI模式,让中文字体不再模糊
  8. PostgreSQL 修改默认用户 postgres 的密码 - 图形化界面操作
  9. linux卸载libc6,更新出问题,libc6-dev : 依赖: libc6
  10. Blender基础技巧小结