Home > other >  Why is basePackageClasses (@ComponentScan) "Type-Safe"?
Why is basePackageClasses (@ComponentScan) "Type-Safe"?

Time:01-31

Can someone help with meaning of Type-Safety in this context?

I'm somehow not very clear with the understanding of the Javadoc - https://docs.spring.io/spring-framework/docs/3.1.4.RELEASE/javadoc-api/org/springframework/context/annotation/ComponentScan.html#basePackages()

CodePudding user response:

public @interface ComponentScan {
  
  String[] basePackages() default {};
  Class<?>[] basePackageClasses() default {};
 
}

It means both basePackages and basePackageClasses provide the same function but basePackageClasses has the type-safe advantages.

Type-safe advantages can help you to know if you really configure that value as the correct type before you really execute the application mainly because if you configure the value incorrectly , the compiler will not let you to compile and hence you cannot execute the application. So we say type safety can help to detect errors at compile time rather then runtime.

Back to this example , as the basePackages type is String , you can configure it to any values even it is an invalid package name and you can still compile and execute the application but it will throw exception when if tries to scan the components from the packages since they are invalid.

But as the basePackageClasses 's type is Class , if you configure it as an invalid package name , it will fail to compile and you cannot execute the application. So it helps to check the package you configure are really the valid one before you really execute the application.

  •  Tags:  
  • Related