@Component
The @Component annotation signals Spring's IoC container to automatically detect and register the class as a bean during component scanning.
@Component
public class UserRole {
@Value("1")
private Long userId;
@Value("user_role_admin")
private String roleName;
@Value("administrative role")
private String description;
// Getters and setters omitted for brevity
}
@Autowired
The @Autowired annotation instructs Spring to inject a dependency by type. It can be applied to fields, constructors, or setter methods.
@Component
public class UserRoleService implements RoleManager {
@Autowired
private UserRole userRole;
// Business methods...
}
@Qualifier
When multiple beans implement the same interface, @Autowired alone cannot resolve which one to inject. The @Qualifier annotation resolves this ambiguity by specifying the bean name.
@Component
public class RoleHandler {
@Autowired
@Qualifier("advancedRoleImpl")
private RoleManager roleManager;
// Implementation details...
}
@Bean
While @Component works only on classes, @Bean is used on methods within configuration classes to explicitly define a bean.
@Configuration
public class DataSourceConfig {
@Bean(name = "appDataSource")
public DataSource createDataSource() {
Properties props = new Properties();
props.setProperty("driver", "com.mysql.cj.jdbc.Driver");
props.setProperty("url", "jdbc:mysql://localhost:3306/app_db");
// Set username, password, etc.
try {
return BasicDataSourceFactory.createDataSource(props);
} catch (Exception e) {
throw new RuntimeException("Failed to create data source", e);
}
}
}
Consuming the bean:
@Component
public class DataProcessor {
@Autowired
@Qualifier("appDataSource")
private DataSource dataSource;
// Use dataSource...
}
@ImportResource
To integrate legacy XML-based bean definitions into a Java-configured application context, use @ImportResource.
<!-- db-config.xml -->
<bean id="legacyDataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/legacy_db"/>
<!-- other properties -->
</bean>
@Configuration
@ComponentScan(basePackages = "com.example.app")
@ImportResource("classpath:db-config.xml")
public class AppConfig {
// Configuration class
}
Multiple XML files can be combined using the <import/> directive inside an XML file:
<!-- main-config.xml -->
<import resource="db-config.xml"/>
<import resource="cache-config.xml"/>
@Profile
The @Profile annotation allows conditional bean registration based on the active environment profile (e.g., dev, test, prod).
@Configuration
public class EnvironmentSpecificConfig {
@Bean
@Profile("development")
public DataSource devDataSource() {
// Configure development database
return buildDataSource("dev_db");
}
@Bean
@Profile("testing")
public DataSource testDataSource() {
// Configure test database
return buildDataSource("test_db");
}
private DataSource buildDataSource(String dbName) {
// Shared logic to construct DataSource
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.build();
}
}
Activate a profile via JVM argument:
-Dspring.profiles.active=development
Or in tests using:
@ActiveProfiles("testing")
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceIntegrationTest {
// Test cases
}
@PropertySource
Use @PropertySource to load external property files into the Spring environment.
# application.properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/myapp
db.username=root
db.password=secret
@Configuration
@PropertySource(
value = "classpath:application.properties",
ignoreResourceNotFound = true
)
public class PropertyConfig {
// Access properties via @Value or Environment
}
The ignoreResourceNotFound = true option prevents startup failure if the file is missing.