Java 将配置注入到配置类的属性中供全局使用【开发记录】

解决方案:读取配置文件,将配置文件中的配置注入到配置类的属性中,供全局使用。

注意:下面所有代码皆为实例代码,并无任务业务含义,本篇文章仅供学习使用,如有侵权请联系本人进行删除,如果转载请注明出处。

一、添加白名单方案:

1、增加配置类:在配置类中添加属性,通过set注入的方式,在set方法中根据逗号分隔字符串,并添加到白名单set集合中,提供checkContractActivateCustomer方法用于判断是否在白名单中。

package com.xx.xx.xxxx.xxxx.core.config;

public class PropertyConfiguration {

	private static final Logger logger = LoggerFactory.getLogger(PropertyConfiguration.class);
	
	/**
     * 配置字符串示例
     */
    private String contractActivateCustomer;

    /**
     * 配置字符串对应的集合
     */
    private Set<String> contractActivateCustomerSet;

	public String getContractActivateCustomer() {
        return contractActivateCustomer;
    }

    public void setContractActivateCustomer(String contractActivateCustomer) {
        logger.info("配置的字符串示例:{}", contractActivateCustomer);
        this.contractActivateCustomer = contractActivateCustomer;
        this.contractActivateCustomerSet = Sets.newHashSet();
        if (StringUtils.isNotBlank(contractActivateCustomer)) {
            final String[] split = contractActivateCustomer.split(",");
            if (split.length > 0) {
                for (String customer : split) {
                    if (StringUtils.isNotBlank(customer)) {
                        this.contractActivateCustomerSet.add(customer);
                    }
                }
            }
        }
    }

    public boolean checkContractActivateCustomer(String customerCode) {
        return this.contractActivateCustomerSet.contains(customerCode);
    }
}

2、在xml文件中注册上面的bean:

在web.xml文件中配置自定义xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
	<display-name>springmvc</display-name>
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/spring-context.xml</param-value>
	</context-param>
</web-app>

在spring-context.xml下导入所有相关的自定义xml文件和配置文件:

<?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:aop="http://www.springframework.org/schema/aop"
	   xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<import resource="demo.xml" />
	
	<bean id="propertiesAll"
		class="org.springframework.beans.factory.config.PropertiesFactoryBean">
		<property name="ignoreResourceNotFound" value="true" />
		<property name="localOverride" value="true" />
		<property name="fileEncoding" value="utf-8" />
		<property name="locations">
			<list>
				<value>classpath:configure/demo.properties</value><!-- 统一配置中心 -->
			</list>
		</property>
	</bean>
</beans>

在demo.xml文件中注册上述配置类对应的bean:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<!-- PropertyConfiguration 配置 begin -->
    <bean name="propertyConfiguration" class="com.xx.xx.xxxx.xxxx.core.config.PropertyConfiguration">
		<!-- 示例属性 -->
        <property name="contractActivateCustomer" value="${contractActivateCustomer}"/>
	</bean>
	
</beans>

在demo.properties中增加配置:

# 示例配置
contractActivateCustomer=000000001,000000002

3、使用的时候直接依赖注入并调用对应的方法即可:

public class Demo{
	@Autowired
	private PropertyConfiguration propertyConfiguration;//统一配置中心

	public void test(String customer) {
		//判断是否在示例白名单配置中
        if(propertyConfiguration.checkContractActivateCustomer(customer)) {
            System.out.println("在白名单");
        }
	}
}

二、扩展说明:

1)上面是通过xml文件的方式注册bean,我们也可以直接在PropertyConfiguration上添加@Component注解,在属性上添加@Value属性注入默认值。

2)也可以在配置文件中通过xml文件与自己公司的配置中心,或者配置平台想关联,在配置平台进行配置实现热部署。

3)上述配置是一个Stirng类型的字符串,配置的是白名单,也可以配置为布尔类型,用做降级开关(根据业务灵活使用)。

4)上述只是简单的根据逗号分隔,通过配置不同格式的json串,然后在属性对应的set方法中进行自定义解析实现更复杂的逻辑,上述我们添加了字符串对应的集合,也可以根据需求添加map属性等来实现复杂的业务。

三、相对复杂的配置示例:

1、我这里在配置文件中的json串是一个map类型,key是一个事业部,value是一个事业部的类里面包含相关事业部信息。

先看下在demo.properties中配置的json串:

businessInfoStr={"dept01":{"deptNo":"dept01","platformId":"platform01","platformName":"测试事业部1","isvSource":"ISV001"},"dept02":{"deptNo":"dept02","platformId":"platform02","platformName":"测试事业部2","isvSource":"ISV002"}}

格式化以后:

{
    "dept01":{
        "deptNo":"dept01",
        "platformId":"platform01",
        "platformName":"测试事业部1",
        "isvSource":"ISV001"
    },
    "dept02":{
        "deptNo":"dept02",
        "platformId":"platform02",
        "platformName":"测试事业部2",
        "isvSource":"ISV002"
    }
}

2、看下对应的事业部的类:

package com.xx.xx.xxxx.xxxx.xxxx.dto.mq.producer;

import lombok.Data;

import java.io.Serializable;

@Data
public class BusinessInfoDto implements Serializable {

    private static final long serialVersionUID = 1389961305825585636L;

    /**
     * 部门编号
     */
    private String deptNo;

    /**
     * 平台ID
     */
    private String platformId;

    /**
     * 平台名称
     */
    private String platformName;

    private String isvSource;

}

3、在对应的配置类添加属性:下面就是在set方法中解析json串实现自定义注入

package com.xx.xx.xxxx.xxxx.core.config;

public class PropertyConfiguration {

	private static final Logger logger = LoggerFactory.getLogger(PropertyConfiguration.class);
	
	/**
     * 特殊赋值
     */
    private String businessInfoStr;
    /**
     * key:deptNo
     * value:businessInfoDto
     */
    private Map<String, BusinessInfoDto> businessInfoMap;

    public String getBusinessInfoStr() {
        return businessInfoStr;
    }

    public void setBusinessInfoStr(String businessInfoStr) {
        logger.info("特殊赋值配置,businessInfoStr:{}", businessInfoStr);
        this.businessInfoStr = businessInfoStr;
        this.businessInfoMap = Maps.newHashMap();
        try{
            if (StringUtils.isNotBlank(businessInfoStr)) {
                this.businessInfoMap = JSON.parseObject(businessInfoStr, new TypeReference<Map<String, BusinessInfoDto>>() {});
            }
            logger.info("特殊赋值配置,businessInfoMap:{}", businessInfoMap);
        } catch (Exception e) {
            logger.error("特殊赋值配置,解析配置异常,businessInfoStr:" + businessInfoStr, e);
        }
    }

    public Map<String, BusinessInfoDto> getBusinessInfoMap() {
        return businessInfoMap;
    }

    public void setBusinessInfoMap(Map<String, BusinessInfoDto> businessInfoMap) {
        this.businessInfoMap = businessInfoMap;
    }
}

4、使用:

public class Demo {
	@Autowired
    private PropertyConfiguration propertyConfiguration;

	public void test(String deptNo) {
		//查看ucc的配置是否为空
        Map<String, BusinessInfoDto> businessInfoMap = propertyConfiguration.getBusinessInfoMap();
        if(CollectionUtils.isEmpty(businessInfoMap)) {
            return;
        }
        BusinessInfoDto businessInfoDto = businessInfoMap.get(deptNo);
        if(StringUtils.isEmpty(deptNo) || java.util.Objects.isNull(businessInfoDto)) {
            return;
        }
        System.out.println(businessInfoDto.getPlatformId())
	}
}

上面只是一部分实现方式,具体要如何实现要根据自己的业务来灵活运用,举一反三。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你好像很好吃a

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值