在Spring Boot中,可以通过使用父子Spring Boot应用程序上下文来避免类加载多次。

具体实现如下:

  1. 在父应用程序中定义一个配置类,该配置类包含所有共享的bean定义和配置项。

  2. 在子应用程序中,使用@Import注解将父应用程序的配置类导入到子应用程序中。

  3. 在子应用程序中,使用@SpringBootApplication注解或@Import注解导入子应用程序的配置类。

这样,父应用程序中的所有bean都将被子应用程序所共享,并且不会出现类加载多次的情况。

示例代码:

父应用程序中的配置类:

@Configuration
public class SharedConfig {
    //定义共享的bean
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

子应用程序中的配置类:

@Configuration
@Import(SharedConfig.class)
public class ChildConfig {
    //定义子应用程序的bean
    @Bean
    public ChildBean childBean() {
        return new ChildBean();
    }
}

子应用程序的启动类:

@SpringBootApplication
@Import(ChildConfig.class)
public class ChildApplication {
    public static void main(String[] args) {
        SpringApplication.run(ChildApplication.class, args);
    }
}

这样,父应用程序中的MyBean将被子应用程序所共享,而且不会出现类加载多次的情况。

springboot 如何避免类加载多次 具体操作

原文地址: https://www.cveoy.top/t/topic/bFGL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录