在类中的定义的属性我们可以通过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. Spring Cloud Alibaba:Sentinel 热点参数限流
  2. win7中cookie的保存位置
  3. docker 安装 oracle 11g
  4. 微软同步框架入门之五--使用WCF同步远程数据
  5. python天气查询小程序加背景图_Python查询天气小程序
  6. 手机安装python3.5_CentOS 7安装Python3.5
  7. MySql command line client 命令系列
  8. 利用zabbix监控ogg进程(Windows平台下)
  9. java 镶嵌创建线程_请教一个 Java 多线程嵌套使用的问题
  10. 【元胞自动机】基于matlab元胞自动机双边教室疏散【含Matlab源码 1208期】
  11. Java多线程编程实战指南(核心篇)读书笔记(二)
  12. excel常用函数公式及技巧搜集4
  13. 2022熔化焊接与热切割复训题库模拟考试平台操作
  14. 论文中怎么写F检验值
  15. Java基础篇---练习:类的设计
  16. .NET EF~Entity Framework详解(lambda表达式、linq到EF)
  17. [原创]佰志达SBO网上商城系统业务框架介绍
  18. Unity 2D横版闯关游戏 (JUNGLE RULES)
  19. contiki-6lowpan开发环境之搭建
  20. 基于支持向量机的谐波分析研究与实现

热门文章

  1. layui中模板的使用
  2. SpringCloud无介绍快使用,nacos配置中心的基本使用(十九)
  3. A-LOAM安装与配置
  4. 2022上海快递物流展,上海快递展,砥砺前行-移师上海新国际博览中心
  5. 史上最全,Spring Boot入门篇总结,收藏起来慢慢看
  6. BigDecimal.setScale用法
  7. 如何判断Windows程序是32位还是64位
  8. 【转载】简评黑客利器——中国菜刀
  9. 十进制(10)与64进制互相转换算法
  10. anki android自动同步,AnkiApp下载-暗记AnkiApp抽认卡记忆神器app 3.1.4 安卓版-我游网...