📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Use Java-Based Configuration (@Configuration and @Bean)
Third-Party Library Integration
Scenario: You're integrating with a third-party library that provides a PaymentGateway class. This class isn't annotated with any Spring annotations, but you need to create and manage its lifecycle using Spring.@Configuration
public class PaymentConfig {
@Bean
public PaymentGateway paymentGateway() {
return new PaymentGateway(...);
}
}
Dynamic Bean Creation Based on Conditions
@Configuration
public class DatabaseConfig {
@Bean
public DatabaseConnector databaseConnector() {
if (/* some condition */) {
return new MySQLDatabaseConnector();
} else {
return new PostgreSQLDatabaseConnector();
}
}
}
Advanced Configuration Using Externalized Values
@Configuration
public class DatabaseConfig {
@Value("${db.url}")
private String url;
@Value("${db.username}")
private String username;
@Value("${db.password}")
private String password;
@Bean
public DataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
Few More Use Cases
Suppose you want to create different beans based on a profile (e.g., dev, test, prod) then you can use Java-based configuration.@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplateOne() {
return new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(30))
.build();
}
@Bean
public RestTemplate restTemplateTwo() {
return new RestTemplateBuilder()
.setReadTimeout(Duration.ofSeconds(30))
.build();
}
}
Use Annotation-Based Configuration (@Component and its derivatives)
Automatic Component Scanning
@Service
public class UserService {
// ...
}
@Repository
public class UserRepository {
// ...
}
Clear Semantic Roles in MVC Applications
@RestController
public class UserController {
// ...
}
Autowiring Dependencies
@Service
public class OrderService {
private final OrderRepository repository;
@Autowired
public OrderService(OrderRepository repository) {
this.repository = repository;
}
// ...
}
Conclusion
In a real-world project, you'll most likely use a combination of both approaches, based on the specific needs and constraints you encounter.
Comments
Post a Comment
Leave Comment