Spring Boot modular application dynamic scan new packages

1 day ago 3
ARTICLE AD BOX

I just cannot get this correct:

I have a class with

@SpringBootApplication(scanBasePackages = "hu.xyz.spring") @Command(group = "DeToX base commands") @ShellComponent

Typical code to start:

SpringApplication application = new SpringApplication(any); context = application.run(args);

Later

private static void addPackage(String pkg) { ConfigurableApplicationContext cac = (ConfigurableApplicationContext) Main.ctx(); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) cac.getBeanFactory(); ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry); scanner.scan(pkg); }

In the pkg there is a bean called "xy" and that needs beans that are defined in the same package in a @Configuration

If I add the scanBasePackages to include the pkg, then it all works

The appcontext is AnnotationConfigServletWebApplicationContext and on this refresh() cannot be called twice :(

After addPackage if I getBean("xy") then it throws an exception that the dependency is missing.

How can I have or force the new beans loaded as "hu.xyz.apple.spring" in @SpringBootApplication(scanBasePackages = {next to the others ...})

then it is all ok!

Why cannot I do this runtime? How could I do this runtime? I want the packages to be loaded only if I need them.

The only way I see that is easily possible is: parent-child appcontext.

But then I have issues if I want to register new "CammandRegistration" for the parent I cannot, this runs but it does nto register the command in the Shell that was started by the parent appcontext.

@Bean public CommandRegistration sync() {

Can I somehow enforce to load shell commands dynamically to the parent?

Read Entire Article