In a Spring application, a Java class can be configured as a Spring bean in the following ways:
In traditional Spring applications, beans are defined in an XML configuration file (bean-config.xml
) using the <bean>
tag.
Example:
<bean id="myBean" class="com.example.MyClass"/>
id
: Unique identifier for the bean.class
: Fully qualified class name of the bean.In Spring Boot, XML configuration is often replaced by Java-based configuration using a @Configuration
class and stereotype annotations for user-defined beans.
Stereotype Annotations:
@Component
: General-purpose annotation for any Spring-managed component.@Service
: Indicates a service-layer bean.@Controller
or @RestController
: Indicates a controller-layer bean for handling HTTP requests.Example:
@Service
public class MyService {
// Service logic
}
@Component
, @Service
, @Controller
, or @RestController
and registers them as beans, provided they are in the base package or its sub-packages.For third-party classes (e.g., ModelMapper
, PasswordEncoder
) that cannot be annotated with stereotype annotations (as their source code is not under your control), use the @Bean
annotation in a @Configuration
class.
Example:
@Configuration
public class AppConfig {
@Bean
public ModelMapper modelMapper() {
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration()
.setMatchingStrategy(MatchingStrategies.STRICT) // Only matching property names are transferred
.setPropertyCondition(Conditions.isNotNull()); // Only non-null properties are transferred
return mapper;
}
}