Spring-注入参数详解-[通过util命名空间简化集合类型的配置]

简介: Spring-注入参数详解-[通过util命名空间简化集合类型的配置]

概述


如果希望配置一个集合类型的Bean,而非一个集合类型的属性,则可以通过util命名空间进行配置。

在spring的配置文件中util命名空间类似于java.util包类对应,util命名空间提供了集合相关的配置,在使用命名空间前要导入util命名空间。


步骤

代码已托管到Github—> https://github.com/yangshangwei/SpringMaster


声明命名空间和schema

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    <!-- 命名空间 -->
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    <!-- schema  如果未指定spring-util.xsd,Spring会自动关联到最新版本 -->
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">
.....
</beans>


配置Bean

配置一个Map

POJO类

package com.xgj.ioc.inject.construct.utilSchema;
import java.util.Map;
public class PetShop {
    private Pets pets;
    public void setPets(Pets pets) {
        this.pets = pets;
    }
    /**
     * 
     * 
     * @Title: petsInfo
     * 
     * @Description: 获取容器注入的Map,遍历输出
     * 
     * 
     * @return: void
     */
    public void petsInfo_Map() {
        Map<Integer, String> map = pets.getPetMap();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("编号Key = " + entry.getKey() + ",品种Value = "
                    + entry.getValue());
        }
    }
}


POJO类

package com.xgj.ioc.inject.construct.utilSchema;
import java.util.Map;
public class Pets {
    private Map<Integer, String> petMap;
    public Map<Integer, String> getPetMap() {
        return petMap;
    }
    public void setPetMap(Map<Integer, String> petMap) {
        this.petMap = petMap;
    }
}


配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="petShop" class="com.xgj.ioc.inject.construct.utilSchema.PetShop">
        <property name="pets" ref="pets" />
    </bean>
<!--    第一种写法 ,通过ref引用,此时需要在 uitl-map中声明id 推荐这种写法
    <bean id="pets" class="com.xgj.ioc.inject.construct.utilSchema.Pets">
        <property name="petMap" ref="petMap" />
    </bean>
    <util:map id="petMap" map-class="java.util.HashMap">
        <entry key="101" value="dog" />
        <entry key="103" value="wolf" />
        <entry key="105" value="bird" />
    </util:map>
-->
    <!-- 第二种写法,嵌入内部 -->
    <bean id="pets" class="com.xgj.ioc.inject.construct.utilSchema.Pets">
        <property name="petMap">
            <util:map  map-class="java.util.HashMap"><!-- 可以通过map-class显示指定Map的实现类 -->
                <entry key="101" value="dog" />
                <entry key="103" value="wolf" />
                <entry key="105" value="bird" />
            </util:map>
        </property>
    </bean>
</beans>


测试类

package com.xgj.ioc.inject.construct.utilSchema;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UtilSchemaTest {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:com/xgj/ioc/inject/construct/utilSchema/beans.xml");
        PetShop petShop = ctx.getBean("petShop", PetShop.class);
        petShop.petsInfo_Map();
    }
}


运行结果

20170721141559381.jpg

<util:map>支持key-type和value-type属性,指定Map的键和值的类型

<util:map  map-class="java.util.HashMap" 
            key-type="java.lang.Integer" 
            value-type="java.lang.String">
                <entry key="101" value="dog" />
                <entry key="103" value="wolf" />
                <entry key="105" value="bird" />
            </util:map>



<util:list><util:set>支持value-type属性,指定集合中的值的类型

配置一个Set

mapsetlistproperties实例汇总 代码

配置一个List

mapsetlistproperties实例汇总 代码


配置一个Properties

mapsetlistproperties实例汇总 代码


Map、Set、List、Properties实例汇总

POJO类

package com.xgj.ioc.inject.construct.utilSchema;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class PetShop {
    private Pets pets;
    public void setPets(Pets pets) {
        this.pets = pets;
    }
    /**
     * 
     * 
     * @Title: petsInfo
     * 
     * @Description: 获取容器注入的Map,遍历输出
     * 
     * 
     * @return: void
     */
    public void petsInfo_Map() {
        Map<Integer, String> map = pets.getPetMap();
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("编号Key = " + entry.getKey() + ",品种Value = "
                    + entry.getValue());
        }
    }
    /**
     * 
     * 
     * @Title: petsInfo
     * 
     * @Description: 获取容器注入的List,遍历输出
     * 
     * 
     * @return: void
     */
    public void petsInfo_List() {
        for (int i = 0; i < pets.getPetList().size(); i++) {
            System.out.println("PetShop has " + pets.getPetList().get(i));
        }
    }
    /**
     * 
     * 
     * @Title: petsInfo
     * 
     * @Description: 获取注入的set,遍历输出
     * 
     * 
     * @return: void
     */
    public void petsInfo_Set() {
        Set<String> set = pets.getPetSet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            System.out.println("PetShop has " + it.next());
        }
    }
    /**
     * 
     * 
     * @Title: petsInfo
     * 
     * @Description: 获取容器注入的Properties,遍历输出
     * 
     * 
     * @return: void
     */
    public void petsInfo_Properties() {
        Map<Object, Object> map = pets.getPetProperties();
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            System.out.println("编号Key = " + entry.getKey() + ",品种Value = "
                    + entry.getValue());
        }
    }
}


POJO类

package com.xgj.ioc.inject.construct.utilSchema;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class Pets {
    private Map<Integer, String> petMap;
    private List<String> petList;
    private Set<String> petSet;
    private Properties petProperties;
    public Properties getPetProperties() {
        return petProperties;
    }
    public void setPetProperties(Properties petProperties) {
        this.petProperties = petProperties;
    }
    public Set<String> getPetSet() {
        return petSet;
    }
    public void setPetSet(Set<String> petSet) {
        this.petSet = petSet;
    }
    public List<String> getPetList() {
        return petList;
    }
    public void setPetList(List<String> petList) {
        this.petList = petList;
    }
    public Map<Integer, String> getPetMap() {
        return petMap;
    }
    public void setPetMap(Map<Integer, String> petMap) {
        this.petMap = petMap;
    }
}


配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="petShop" class="com.xgj.ioc.inject.construct.utilSchema.PetShop">
        <property name="pets" ref="pets" />
    </bean>
 <!--  第一种写法 ,通过ref引用,此时需要在 uitl-map中声明id 推荐这种写法 -->
 <!-- property 中的name对应类中属性, ref对应uitl的id -->
    <bean id="pets" class="com.xgj.ioc.inject.construct.utilSchema.Pets">
        <property name="petMap" ref="petMap"/>
        <property name="petList" ref="petList"/>
        <property name="petSet" ref="petSet"/>
        <property name="petProperties" ref="petProperties"/>
    </bean>
    <!-- 配置一个Map集合 -->
    <util:map id="petMap" map-class="java.util.HashMap">
        <entry key="101" value="dog" />
        <entry key="103" value="wolf" />
        <entry key="105" value="bird" />
    </util:map>
    <!-- 配置一个List集合 -->
    <util:list id="petList" list-class="java.util.ArrayList" value-type="java.lang.String">
        <value>DOG</value>
        <value>CAT</value>
        <value>BIRD</value>
    </util:list>
     <!-- util配置一个Set集合 -->
    <util:set id="petSet" set-class="java.util.HashSet" value-type="java.lang.String">
        <value>牛</value>
        <value>马</value>
        <value>狗</value>
    </util:set>
    <!--配置一个 Properties-->
    <util:properties id="petProperties">
            <prop key="151">PIG</prop>
            <prop key="153">PINGUIN</prop>
    </util:properties>
    <!-- 第二种写法,嵌入内部 
    <bean id="pets" class="com.xgj.ioc.inject.construct.utilSchema.Pets">
        <property name="petMap">
            <util:map  map-class="java.util.HashMap" 
                       key-type="java.lang.Integer" 
                       value-type="java.lang.String"> 可以通过map-class显示指定Map的实现类
                <entry key="101" value="dog" />
                <entry key="103" value="wolf" />
                <entry key="105" value="bird" />
            </util:map>
        </property>
    </bean>
     -->
</beans>


测试类

package com.xgj.ioc.inject.construct.utilSchema;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UtilSchemaTest {
    static Logger logger = Logger.getLogger(UtilSchemaTest.class);
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "classpath:com/xgj/ioc/inject/construct/utilSchema/beans.xml");
        PetShop petShop = ctx.getBean("petShop", PetShop.class);
        logger.info("---------------Map--------------------");
        petShop.petsInfo_Map();
        logger.info("---------------List--------------------");
        petShop.petsInfo_List();
        logger.info("---------------Set--------------------");
        petShop.petsInfo_Set();
        logger.info("---------------Properties--------------------");
        petShop.petsInfo_Properties();
    }
}


运行结果:


20170721144035843.jpg

相关文章
|
7月前
|
Java 关系型数据库 MySQL
Spring Boot自动配置:魔法背后的秘密
Spring Boot 自动配置揭秘:只需简单配置即可启动项目,背后依赖“约定大于配置”与条件化装配。核心在于 `@EnableAutoConfiguration` 注解与 `@Conditional` 系列条件判断,通过 `spring.factories` 或 `AutoConfiguration.imports` 加载配置类,实现按需自动装配 Bean。
|
7月前
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
2487 0
|
6月前
|
前端开发 Java 应用服务中间件
《深入理解Spring》 Spring Boot——约定优于配置的革命者
Spring Boot基于“约定优于配置”理念,通过自动配置、起步依赖、嵌入式容器和Actuator四大特性,简化Spring应用的开发与部署,提升效率,降低门槛,成为现代Java开发的事实标准。
|
7月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
1317 5
|
7月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
378 0
探索Spring Boot的@Conditional注解的上下文配置
|
9月前
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
1308 0
|
10月前
|
人工智能 Java 测试技术
Spring Boot 集成 JUnit 单元测试
本文介绍了在Spring Boot中使用JUnit 5进行单元测试的常用方法与技巧,包括添加依赖、编写测试类、使用@SpringBootTest参数、自动装配测试模块(如JSON、MVC、WebFlux、JDBC等),以及@MockBean和@SpyBean的应用。内容实用,适合Java开发者参考学习。
1119 0
|
6月前
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
552 4
|
6月前
|
Java 测试技术 数据库连接
【SpringBoot(四)】还不懂文件上传?JUnit使用?本文带你了解SpringBoot的文件上传、异常处理、组件注入等知识!并且带你领悟JUnit单元测试的使用!
Spring专栏第四章,本文带你上手 SpringBoot 的文件上传、异常处理、组件注入等功能 并且为你演示Junit5的基础上手体验
1074 3
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
506 0
下一篇
开通oss服务