canna-cloud【五】spring boot延迟自定义枚举的static值初始化

版权声明: https://blog.csdn.net/jiangxuexuanshuang/article/details/88993800

1、自定义注解:InitEnum

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InitEnum {
    public static final Object[] NULL_ITEM = { "" };
    public static final Class[] parameterTypes = { String.class };
}

2、反射创建实例

    public static <T> T getInstance(Class<T> clazz) throws Exception {
		try {
			return clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			log.info("", e);
			throw new Exception("实例化失败");
		}
    }

3、在需要的初始化对象中添加注解

@InitEnum
public class FileModuleEnum {

	private static final Map<String, FileModuleEnum> nameEnumMap = new ConcurrentHashMap<>();

	protected FileModuleEnum(String name) {
		if (!nameEnumMap.containsKey(name)) {
			nameEnumMap.put(name, this);
		}
	}

	public static FileModuleEnum valueOf(String name) {
		if (name == null)
			throw new NullPointerException("Name is null");

		FileModuleEnum result = nameEnumMap.get(name);
		if (result != null) {
			return result;
		}

		throw new IllegalArgumentException("No enum constant exists, name is." + name);
	}

}

4、监听启动后进行初始化

@Log4j2
@Component
@Order(value = 0)
public class EndStartedListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private SpringClassService springClassService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        try {
            this.initEnum();
        } catch (Exception e) {
            log.error("", e);
        }

    }

    private void initEnum() throws Exception {
        List<Class> classList = springClassService.listAllClass();
        for (Class clazz: classList) {
            if (clazz.isAnnotationPresent(InitEnum.class)) {
                Object temp = BeanTransferUtils.getInstance(clazz, InitEnum.parameterTypes, InitEnum.NULL_ITEM);
                temp = null;
            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/jiangxuexuanshuang/article/details/88993800
今日推荐