package com.haha.admin;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.Ordered;

@SpringBootApplication
@ComponentScan(basePackages = {"com.haha"})
@MapperScan("com.haha.mapper")
public class AdminApplication {

    @Bean
    public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
        return new PriorityOrderedBeanFactoryPostProcessor();
    }

    public static class PriorityOrderedBeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {
        @Override
        public int getOrder() {
            return Ordered.HIGHEST_PRECEDENCE;
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) {
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
                Object attr = beanDefinition.getAttribute("factoryBeanObjectType");
                if (attr instanceof String) {
                    try {
                        // 将 String 类型的类名转换为真正的 Class 对象,解决 Spring 6.2+ (Boot 3.4/3.5) 的类型检查问题
                        beanDefinition.setAttribute("factoryBeanObjectType", Class.forName((String) attr));
                    } catch (Throwable e) {
                        // 转换失败则移除该属性,由 Spring 自行推断
                        beanDefinition.removeAttribute("factoryBeanObjectType");
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        SpringApplication.run(AdminApplication.class, args);
    }
}
