SpringBoot和Spring排除某个Config文件不加载

阿里云的Schedulerx启动时需要阿里的tomcat,需要注册到阿里服务器上,不能使用懒加载方式,但测试时注入不成功,所以测试需要排除Schedulerx的Bean

方法:

1、Schedulerx的Bean单独放一个Config文件(测试不想初始化的Bean单独放一个文件)

一、SpringBoot测试去除某个配置文件不加载。 

package com.suyun.svop.admin;

import com.suyun.svop.SvopAdminApplication;
import com.suyun.svop.cache.CorpStationCache;
import com.suyun.svop.config.SchedulerxConfig;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Description:
 *
 * @Author: leo.xiong
 * @CreateDate: 2020/12/07 14:21
 * @Email: [email protected]
 * @Since:
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SvopAdminApplication.class)
public class TestCache {

    @MockBean
    private CorpStationCache corpStationCache;
    //排除不加载的配置文件,里面的bean不会加载,也可以是某个Bean对象
    @MockBean
    private SchedulerxConfig schedulerxConfig;

    @Test
    public void testMultithreadingCache() {
        int size = 500;
        String cacheKey = "test:key";
        Set<Thread> threadSet = new HashSet<>();
        for (int i = 0; i < size; i++) {
            threadSet.add(new Thread(new TestPutClass(corpStationCache, cacheKey)));
        }
        for (int i = 0; i < size; i++) {
            threadSet.add(new Thread(new TestGetClass(corpStationCache, cacheKey)));
        }
        for (int i = 0; i < size; i++) {
            threadSet.add(new Thread(new TestDeleteClass(corpStationCache, cacheKey)));
        }
        for (Thread thread : threadSet) {
            thread.start();
        }
    }
}

class TestPutClass implements Runnable {
    private CorpStationCache corpStationCache;

    private String cacheKey;

    public TestPutClass(CorpStationCache corpStationCache, String cacheKey) {
        this.corpStationCache = corpStationCache;
        this.cacheKey = cacheKey;
    }

    @Override
    public void run() {
        List<Object> list = Lists.newArrayList("1", "2");
        corpStationCache.put(cacheKey, list);
        System.out.println("插入数据》》》》》》》》》》》》》》》");
    }
}

class TestDeleteClass implements Runnable {
    private CorpStationCache corpStationCache;

    private String cacheKey;

    public TestDeleteClass(CorpStationCache corpStationCache, String cacheKey) {
        this.corpStationCache = corpStationCache;
        this.cacheKey = cacheKey;
    }


    @Override
    public void run() {
        corpStationCache.delete(cacheKey);
        System.out.println("删除数据》》》》》》》》》》》》》》》");
    }
}

class TestGetClass implements Runnable {
    private CorpStationCache corpStationCache;

    private String cacheKey;

    public TestGetClass(CorpStationCache corpStationCache, String cacheKey) {
        this.corpStationCache = corpStationCache;
        this.cacheKey = cacheKey;
    }


    @Override
    public void run() {
        List<Object> list = corpStationCache.get(cacheKey);
        System.out.println("查询数据》》》》》》》》》》》》》》》list" + list);
        if (list != null) {
            try {
                System.out.println("开始读取》》》》》》》》》");
                Thread.sleep(2000);
                System.out.println("读取数据》》》》》》》》" + list.get(0));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//排除不加载的配置文件,里面的bean不会加载,也可以是某个Bean对象
@MockBean
private SchedulerxConfig schedulerxConfig;

二、Spring测试去除某个配置文件不加载。 

package com.suyun.configuration;

import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Description:
 * AppConfig排除测试无需要加载的config文件
 * SchedulerxConfig引入AppConfig排除的config文件
 * @Author: leo.xiong
 * @CreateDate: 2021/5/8 11:57
 * @Email: [email protected]
 * @Since:
 */
@ComponentScan(includeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = AppConfig.class)
        , @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)
        , @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = SchedulerxConfig.class)})
@EnableWebMvc
@EnableAsync
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
    }

    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");
        registry.addInterceptor(localeChangeInterceptor);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*");
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
                .indentOutput(true)
                .dateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                .timeZone("GMT+8")//设置统一时区信息东八区
                .modulesToInstall(new ParameterNamesModule());
        Charset s = Charset.forName("UTF-8");
        converters.add(new StringHttpMessageConverter(s));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }


}

@ComponentScan(includeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = AppConfig.class)
        , @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)
        , @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = SchedulerxConfig.class)})

@Configuration("appConfig")
@ComponentScan(basePackages = {"com.suyun", "com.server", "com.utils"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = SchedulerxConfig.class)})
@ImportResource({"classpath:spring-dubbo.xml", "classpath:spring-mvc.xml"})
@PropertySource({"classpath:webConfig.properties", "classpath:kafka.properties"})
@MapperScan("com.suyun.modules.*.dao")
@EnableTransactionManagement
@EnableCaching
@EnableAspectJAutoProxy(exposeProxy = true)
public class AppConfig {

}

@ComponentScan(basePackages = {"com.suyun", "com.server", "com.utils"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = SchedulerxConfig.class)})

package com.test;

import com.suyun.configuration.AppConfig;
import com.suyun.configuration.SchedulerxConfig;
import com.suyun.message.listener.DurabilitySummaryListener;
import com.taobao.hsf.lightapi.ServiceFactory;
import dto.VehicleReportDataDto;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.io.IOException;
import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * Description:
 *
 * @Author: leo.xiong
 * @CreateDate: 2021/02/03 10:52
 * @Email: [email protected]
 * @Since:
 */
@RunWith(SpringJUnit4ClassRunner.class)
@org.springframework.context.annotation.Configuration("masterDataServiceConfiguration")
@ContextConfiguration(classes = {AppConfig.class})
public class RedisTaskTest {

    // 这里设置Pandora地址,参数是sar包所在目录,如这里我的sar包地址是D:/tomcat/taobao-tomcat-7.0.59/deploy/taobao-hsf.sar,则只取前面的地址即可
    private static final ServiceFactory FACTORY = ServiceFactory.getInstanceWithPath("D:/tomcat/taobao-tomcat-7.0.59/deploy");

    @Autowired
    private DurabilitySummaryListener durabilitySummaryListener;

    @Test
    public void testRedisChannel() throws IOException {
        VehicleReportDataDto vehicleReportDataDto = new VehicleReportDataDto();
        vehicleReportDataDto.setBusId("b1cd318ee7a64bceb5e2926e4c2a876e");
        vehicleReportDataDto.setDagId(378350104L);
        vehicleReportDataDto.setIsReference("no");
        vehicleReportDataDto.setPalteNo("测试台架2");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        vehicleReportDataDto.setStatisticsDay(Date.from(LocalDateTime.parse("2021-05-06 00:00:00", dateTimeFormatter).toInstant(ZoneOffset.of("+8"))));
        vehicleReportDataDto.setStatus("success");
        vehicleReportDataDto.setTableName("veh_day_data_distinct_unzip_202105");
        vehicleReportDataDto.setTaskId("f206602851e64631b544c40adca2483a");
        durabilitySummaryListener.buildMessage(vehicleReportDataDto);
    }
}

@ContextConfiguration(classes = {AppConfig.class})

猜你喜欢

转载自blog.csdn.net/xionglangs/article/details/116528981