Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between register() and @ComponentScan

Tags:

java

spring

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 ?

like image 864
Gutter Overflow FKuAll Avatar asked May 26 '26 20:05

Gutter Overflow FKuAll


1 Answers

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 { ... }

XML

<bean id="fooService" class="FooService"/>

XML with Component Scan

@Service
public class FooService { ... }
<context:component-scan />

Java Config

@Bean
public FooService fooService() {
  return new FooService();
}

Java Config with Component Scan

@Service
public class FooService { ... }
@ComponentScan
public FooConfig {}

Functional Style DSL

context.registerbean("fooService", FooService.class, () -> new FooService());

Properties Based

fooService.(class)=FooService

Then use the PropertiesBeanDefinitionReader to load it (going to be deprecated or removed as of Spring 5.3).

like image 195
M. Deinum Avatar answered May 28 '26 11:05

M. Deinum