Java、Rust 技术交流群: 783303214
一、背景
最近有小朋友问我,怎么样在.properties文件中配置数组参数,我给他举了上篇文章中的注解@ConfigurationProperties("xxx"),但是遗憾的是他们的项目并没有接入spring,而是用netty写的什么sdk吧,我猜,所以上述注解无法使用,加上自己很久没有玩反射了,就将就着写了一个demo,以供初学者借鉴,话不多说,不懂的看注释,写的还是比较详细。
二、代码实现
首先,我们定义一个注解类,并规定好其作用域等信息
package com.github;
import java.lang.annotation.*;
/**
* @Author: BBSee
* @E-mail: rolltion.zhang@foxmail.com
* @CreateDate: 16:16 2019/7/22 0022
* @Description:
*/
@Target({ ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface BBSee {
String value() default "";
/**
* The prefix of your properties fields
*/
String prefix() default "";
/**
* These two boolean fields have not been analysed at present
* if you do have this requirement,add it to the {@link com.github.PropertiesLoader<>}
* @return
*/
boolean ignoreInvalidFields() default false;
boolean ignoreUnknownFields() default true;
}
我们规定该注解只能使用于类上,即我们的pojo类上,prefix为配置文件中的字段前缀,接下来,我们定义注解解释器并对配置文件进行获取,由于时间不是很多,所以只写了核心的功能,即注解加载数组信息,根据pojo类的字段名称加载配置信息等,会有些bug,但是都无关痛痒,具体的看代码注释:
package com.github;
import com.github.conf.DataSourceNumberProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Fiel