Enterprise Fortgeschritten

Spring XML-Bean-Konfiguration vs. annotationsbasiert

Ersetze ausführliche Spring-XML-Bean-Definitionen durch prägnante annotationsbasierte Konfiguration mit Spring Boot.

✕ Spring (XML)
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userRepository"
          class="com.example.UserRepository">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="userService"
          class="com.example.UserService">
        <property name="repository" ref="userRepository"/>
    </bean>

</beans>
✓ Spring Boot 3+
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@Repository
public class UserRepository {
    private final JdbcTemplate jdbc;

    public UserRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }
}

@Service
public class UserService {
    private final UserRepository repository;

    public UserService(UserRepository repository) {
        this.repository = repository;
    }
}
Problem mit diesem Code entdeckt? Sag uns Bescheid.
🚫

Kein XML

@SpringBootApplication aktiviert Component-Scanning und Auto-Konfiguration und eliminiert alle XML-Verdrahtungsdateien.

💉

Konstruktorinjektion

Spring injiziert Abhängigkeiten automatisch über Konstruktoren, was Beans einfacher zu testen und nachzuvollziehen macht.

Auto-Konfiguration

Spring Boot konfiguriert DataSource, JPA und andere Infrastruktur vom Classpath ohne Boilerplate.

Alter Ansatz
XML-Bean-Definitionen
Moderner Ansatz
Annotationsbasierte Beans
Seit JDK
17
Schwierigkeitsgrad
Fortgeschritten
Spring XML-Bean-Konfiguration vs. annotationsbasiert
Verfügbar

Weitgehend verfügbar seit Spring Boot 1.0 (April 2014); Spring Boot 3 erfordert Java 17+

Traditionelle Spring-Anwendungen verdrahteten Beans über XML-Konfigurationsdateien und deklarierten jede Klasse mit ihren Abhängigkeiten als ausführliche <bean>-Elemente. Obwohl Annotationsunterstützung seit Spring 2.5 existierte, blieb XML der vorherrschende Ansatz, bis Spring Boot Auto-Konfiguration einführte. Spring Boot erkennt Beans, die mit @Component, @Service, @Repository und @Controller annotiert sind, per Classpath-Scanning, erfüllt Abhängigkeiten automatisch per Konstruktorinjektion und konfiguriert Infrastruktur wie DataSource vom Classpath — was alle XML-Verdrahtungsdateien eliminiert.

Teilen 𝕏 🦋 in