I'm new to Spring.
What does the register(Class<?>... componentClasses) method do ?
Is it just like registering a bean when we are using @ComponentScan to register the beans in the container?
What are differences between register(Class<?>... componentClasses) and @ComponentScan ?
There is no difference. It are different ways of registering a bean in the Spring application context. Like you can use XML or Java based configuration. In the end it is all metadata used to construct the ApplicationContext. The one with the registerBean is considered the (sort of) functional style of registering beans. This is mainly being utilized to be able to write the Kotlin bean registration DSL (AFAIK).
Although they work differently, i.e. registering components directly as opposed to scan the classpath for beans that match the selection criteria (default is to detect @Component). The end result is the same.
For all of them a BeanDefinition is being created by Spring. The exact type of BeanDefinition will differ based on the type of configuration. For XML and Properties based it will, generally, be a RootBeanDefinition, when detected with component scanning a ScannedBeanDefinition etc. For the registerBean it will be a ClassDerivedBeanDefinition.
BeanDefinitions are the recipes on how to create beans.
All the different ways as shown below will have the same end result. An ApplicationContext with a FooService.
public class FooService { ... }
<bean id="fooService" class="FooService"/>
@Service
public class FooService { ... }
<context:component-scan />
@Bean
public FooService fooService() {
return new FooService();
}
@Service
public class FooService { ... }
@ComponentScan
public FooConfig {}
context.registerbean("fooService", FooService.class, () -> new FooService());
fooService.(class)=FooService
Then use the PropertiesBeanDefinitionReader to load it (going to be deprecated or removed as of Spring 5.3).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With