Spring Configuration
Spring is flexible: you can configure beans using XML, annotations, or Java-based configuration. Each has its own advantages.
1. XML Configuration (traditional): Beans are defined in an XML file.
<?xml version="1.0" encoding="UTF-8"?>
<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="myBean" class="com.example.MyBean"/>
</beans>
2. Annotation-based Configuration: Use annotations like
@Component, @Service, @Repository on classes, and @Autowired for injection. You need to enable component scanning.@Component
public class MyBean {
public void doSomething() { ... }
}
// In XML config, enable scanning:
<context:component-scan base-package="com.example"/>
3. Java-based Configuration: Use
@Configuration and @Bean methods. This is type‑safe and preferred in modern Spring (especially Spring Boot).@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
Two Minute Drill
- Spring supports three configuration styles: XML, annotations, and Java config.
- XML is traditional but verbose; annotations reduce boilerplate; Java config is type‑safe and widely used.
- Component scanning (
<context:component-scan>or@ComponentScan) is needed for annotations. - Java config uses
@Configuration+@Beanmethods.
Need more clarification?
Drop us an email at career@quipoinfotech.com
