Konfiguracja XML Spring kontra adnotacje
Zastąp rozwlekłe definicje beanów XML Spring zwięzłą konfiguracją sterowaną adnotacjami w Spring Boot.
<!-- 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>
@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;
}
}
Bez XML
@SpringBootApplication wyzwala skanowanie komponentów i auto-konfigurację, eliminując wszystkie pliki XML.
Wstrzykiwanie konstruktorem
Spring automatycznie wstrzykuje zależności przez konstruktory, ułatwiając testowanie i rozumowanie o beanach.
Auto-konfiguracja
Spring Boot konfiguruje DataSource, JPA i inną infrastrukturę z classpath bez boilerplate.
Szeroko dostępne od Spring Boot 1.0 (kwiecień 2014); Spring Boot 3 wymaga Java 17+
Tradycyjne aplikacje Spring łączyły beany przez pliki konfiguracyjne XML, deklarując każdą klasę i jej zależności jako rozwlekłe elementy <bean>. Choć wsparcie adnotacji istniało od Spring 2.5, XML pozostawał dominującym podejściem do czasu gdy Spring Boot wprowadził auto-konfigurację. Spring Boot wykrywa beany adnotowane @Component, @Service, @Repository i @Controller przez skanowanie classpath, automatycznie zaspokaja zależności przez wstrzykiwanie konstruktorem i konfiguruje infrastrukturę jak DataSource z classpath — eliminując wszystkie pliki XML.