1. Ways to Configure a Java Class as a Spring Bean

In a Spring application, a Java class can be configured as a Spring bean in the following ways:

1.1 Pure XML Approach

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"/>

1.2 Spring Boot: No XML Approach (Using Stereotype Annotations)

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:

Example:

@Service
public class MyService {
    // Service logic
}

1.3 Configuring Third-Party Classes as Spring Beans

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;
    }
}