1. 程式人生 > 其它 >forest無法掃描指定包介面問題解決

forest無法掃描指定包介面問題解決

技術標籤:java

0.專案為dubbo服務 無法使用註解注入

@ForestScan(basePackages = "com.yoursite.client")

1.掃描指定路徑下的java類 手動交給spring管理

import com.dtflys.forest.config.ForestConfiguration;
import com.zjy.zjeframework.core.exception.SimpleException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.stereotype.Component;

/**
 * @author enzo
 * @date 2020/12/24 11:10
 * @description http相關bean初始化
 */
@Component
public class ForestBeanInitialize implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        ForestConfiguration configuration = ForestConfiguration.getDefaultConfiguration();
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            MetadataReaderFactory metaReader = new CachingMetadataReaderFactory();
            //根據類路徑載入所有的類
            Resource[] resources = resolver.getResources("classpath*:com/zjy/iot/smart/community/api/**/*.class");
            ClassLoader loader = ClassLoader.getSystemClassLoader();
            for (Resource resource : resources) {
                MetadataReader reader = metaReader.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                Class<?> clazz = loader.loadClass(className);
                //使用forest建立例項
                Object instance = configuration.createInstance(clazz);
                //註冊到spring中
                configurableListableBeanFactory.registerSingleton(className, instance);
            }
        } catch (Exception e) {
            throw new SimpleException();
        }
    }
    
}

2.呼叫service

@Resource
private LoginService loginService;