3

I have project setup using Spring boot that loads individual components on startup. Each individual packages contain its own datasource, processes, etc. I can simply use this and it works fine

@SpringBootApplication(scanBasePackages = {
    "com.package1",
    "com.package2",
    "com.package3"
})
public class Application extends SpringBootServletInitializer{
    public static void main(String[] args){
        SpringApplication.run(Application.class,args)        
    }
}

But currently, the number of indiviual projects are getting bigger. Is it possible to put the list of the components / packages to scan in an external properties file or spring vault? I'm not sure how to retrieve it, and is it possible to retrieve the properties before the boot?


Edit:

Currently I tried this:

@Import(AppConfig.class)
public class Application extends SpringBootServletInitializer{
    public static void main(String[] args){
        SpringApplication.run(Application.class,args)        
    }
}


@Configuration
@ComponentScan(basePackages = {$app.packages})
@EnableAutoConfiguration
public class AppConfig {
}

//in my properties file
app.packages = ["com.package1","com.package2","com.package3"]

but its not working

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
pokken
  • 327
  • 1
  • 15

2 Answers2

5

You are on right track but couple of minor mistakes, specify the packages by common separated in yml or properties file

app.packages = com.package1,com.package2,com.package3

Then use Spring Expression Language in @ComponentScan annotation

@ComponentScan(basePackages = {"${app.packages}"})
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

This can be done using a static string constant. I tried following and it is working.

ScanBasePackageTestApplication is in 3rd package other than "test.packageOne, test.packageTwo" packages. Then I tried to autowire single class from each of test.packageOne and test.packageTwo into class from main package and it worked fine.

@Configuration
@SpringBootApplication(scanBasePackages = PackagesScanMetaData.PACKAGES_TO_SCAN)
public class ScanBasePackageTestApplication {

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

}

public class PackagesScanMetaData {
    public static final String PACKAGES_TO_SCAN = "test.packageOne, test.packageTwo";

}

In this case you can manage all the to be scanned package list in PackagesScanMetaData class. Hope this helps.

chaitzD
  • 81
  • 5