🚀 Understanding Types of Dependencies in Spring: Primitive, Collection & Reference 🔹 1. Primitive Dependencies Primitive dependencies refer to simple values like int, double, boolean, or String that are injected into a Spring bean. ✔️ Used for configuration values and constants ✔️ Injected using annotations like @Value or XML configuration 📌 Example: Injecting application properties such as server port, database URL, or timeout values. 🔹 2. Collection Dependencies Collection dependencies involve injecting a group of values or objects into a bean using collections like List, Set, or Map. ✔️ Useful when handling multiple values of the same type ✔️ Helps in managing configurable data dynamically 📌 Example: A list of email recipients, supported payment methods, or roles assigned to a user. 🔹 3. Reference Dependencies Reference dependencies are objects (beans) that depend on other objects managed by the Spring container. ✔️ Represents real-world relationships between components ✔️ Promotes loose coupling using Dependency Injection 📌 Example: A Service class depending on a Repository class for database operations. 💡 Key Takeaways Primitive → Simple configuration values Collection → Group of values or beans Reference → One bean depending on another bean ✨ Understanding these dependency types helps in designing flexible and modular applications using Spring. #SpringFramework #Java #DependencyInjection #BackendDevelopment Thanks to Anand Kumar Buddarapu Sir.
Spring Dependency Types: Primitive, Collection & Reference
More Relevant Posts
-
#Post5 In the previous post, we saw how @RequestBody helps us handle request data. Now the next question is 👇 How do we get data from the URL? There are two common ways: • @PathVariable • @RequestParam Let’s understand 👇 👉 @PathVariable Used when the value is part of the URL path Example: GET /users/10 @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User id: " + id; } 👉 @RequestParam Used when the value comes as a query parameter Example: GET /users?id=10 @GetMapping("/users") public String getUser(@RequestParam int id) { return "User id: " + id; } 💡 Key difference: @PathVariable → part of URL @RequestParam → query parameter Key takeaway: Use the right approach based on how data is passed in the request 👍 In the next post, we will explore exception handling in Spring Boot 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
🚀 Multi-Tenant Dynamic DataSource Routing in Spring Boot Today I implemented runtime database switching for a multi-tenant reporting system — here’s what I built and what I learned. ❓ The Problem One application. Multiple customers. Each customer has their own isolated database. How do you dynamically route queries to the correct database at runtime — without restarting the application? ✅ The Solution: Dynamic DataSource Routing Built using 3 core components: 1️⃣ DataSourceResolver - Fetches DB credentials from a configuration table at runtime - Creates a HikariCP connection pool per tenant (cached — created only once) - Sets the current tenant in a ThreadLocal 2️⃣ TenantContext (ThreadLocal) - Stores tenant info per thread - Thread 1 → customer_A_db - Thread 2 → customer_B_db - Ensures zero interference between concurrent users 3️⃣ RoutingDataSource (AbstractRoutingDataSource) - Spring’s built-in routing mechanism - On each DB call: - Reads tenant from ThreadLocal - Selects the correct DataSource - Returns the actual connection - Uses lazy connection fetching (connection created only when query executes) 🔄 Execution Flow queryForList() → RoutingDataSource.getConnection() → determineTargetDataSource() → TenantContext.get() → cache hit → HikariPool → actual connection → query executes → connection returned to pool 💡 Key Insight routingJdbcTemplate does NOT hold a connection. It acts as a proxy — connection is fetched only at query execution time. 🟢 When to Use This Approach - JdbcTemplate-based applications - Small to medium number of tenants - Lightweight solution (no external libraries) 🙌 Final Thoughts Building in public. Still learning and exploring better patterns. Would love to hear how others have implemented multi-tenancy in Spring! #SpringBoot #Java #MultiTenancy #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
Exploring with Spring Beans & Configuration I focused on one of the core building blocks of Spring: Beans. -> What are Spring Beans? Spring Beans are simply objects managed by the Spring container. Instead of manually creating objects using new, Spring takes control and manages their lifecycle. This is where IoC (Inversion of Control) actually becomes real. How Beans are Created I explored different ways to define beans: 1. Using @Component @Component public class UserService { } Spring automatically detects and creates this object. 2. Using @Bean (Manual Configuration) @Configuration public class AppConfig { @Bean public UserService userService() { return new UserService(); } } Gives more control over object creation. Configuration Styles : I learned that Spring supports multiple ways to configure applications: 1) XML Configuration (old way, rarely used now) 2) Java-based Configuration (modern and flexible) 3) Annotation-based Configuration (most commonly used) 4) Spring container = object manager 5) Beans = objects controlled by Spring 6) Configuration = how Spring knows what to create Earlier, I used to write: UserService service = new UserService(); Now Spring does this for me automatically a) Less tight coupling b) Better maintainability c) Cleaner architecture #SpringFramework #Java #BackendDevelopment #LearningJourney EchoBrains
To view or add a comment, sign in
-
-
Doubly Linked List Implementation in Java Today I implemented a Doubly Linked List from scratch to strengthen my understanding of how data structures work internally. What I built: • Converted an array into a Doubly Linked List • Traversed and printed the list • Calculated length of the list • Implemented deletion operations: • Delete head • Delete tail Key Operations Implemented: 1. Convert Array → DLL • Created nodes dynamically • Linked each node using next and back 2. Delete Head • Move head to next node • Remove backward reference 3. Delete Tail • Traverse to last node • Disconnect last node from previous 4. Length Calculation • Traverse the list and count nodes #Java #DataStructures #DSA #BackendJourney #SoftwareDevelopment
To view or add a comment, sign in
-
-
Spring Data Interview Question : Efficient Keyset Pagination with Spring Data WindowIterator Scenario You’re building a Spring Boot API to fetch comments for a post. The table has tens of millions of rows, and users can scroll deeply into the history. Initial Implementation is attached. Problem Observed in Production As users scroll deeper: - Queries slow down dramatically - DB CPU rises - Response times become inconsistent Why offset pagination is inefficient? Checkout detailed questions and answers : https://lnkd.in/ePcwy9tJ Subscribe and join 6.5k java and spring boot devs https://lnkd.in/gwiRqWBV #java #spring #springboot
To view or add a comment, sign in
-
-
Are you still loading everything into memory? Let me ask you something. How many times have you seen this in a codebase? repository.findAll() ☠️ Looks harmless, right? Until it isn’t. That single line can: • Pull millions of records into memory • Fill your Hibernate context • Trigger massive GC pressure • And eventually… crash your application This is not a performance issue. This is an architectural flaw. Most systems don’t fail because of complexity. They fail because of unbounded data processing. You are not controlling how much data your system loads, processes, or returns. And memory… has limits. So what’s the right approach? Stop thinking: "How do I get all the data?" Start thinking: "How do I guarantee I NEVER load too much?" The solution is simple (but often ignored): • Use pagination for APIs • Use streaming for large exports • Process data in controlled chunks • Return DTOs instead of heavy entities • Set hard limits Golden rule: Never load, process, or serialize everything at once. Always paginate, stream, or limit. Most production outages I’ve seen had one thing in common: Someone assumed the data would always be small. It never is. #SoftwareArchitecture #Java #SpringBoot #DistributedSystems #SoftwareEngineering #DesignPatterns
To view or add a comment, sign in
-
-
Just published my first technical article on Dev.to! "Building a Database Engine from Scratch" Covered everything: - B+ Tree implementation in C++ - Java + C++ IPC bridge - Docker deployment - Live analytics dashboard Read here: https://lnkd.in/grR247qE Live Demo: fourmulaquery.onrender.com GitHub: https://lnkd.in/gKrjbYGh #buildinpublic #cpp #java #database
To view or add a comment, sign in
-
🌟 Understanding Entity, Repository, and Service Layers in Spring Boot 📌 A well-structured Spring Boot application follows a layered architecture to ensure clean, maintainable, and scalable code. 👉 Entity Layer Represents the database structure. It defines how data is stored using annotations like @Entity and @Id. 👉 Repository Layer Handles database operations. Using Spring Data JPA, it provides built-in methods like save, find, and delete without writing SQL. 👉 Service Layer Contains the business logic of the application. It processes data, applies rules, and connects the controller with the repository. -->A well-structured application using these layers ensures clean code, scalability, and maintainability, which are essential for real-world backend development. #SpringBoot #Java #BackendDevelopment #SoftwareArchitecture #LearningInPublic
To view or add a comment, sign in
-
-
Is your @Transactional annotation actually doing what you think? 🧐 In Spring Boot, data integrity is everything. But I often see a common trap: Self-invocation. If you call a transactional method from another method within the same class, the Spring Proxy is bypassed. 📉 The result? No transaction starts, and your data might end up inconsistent without any error message. Check: ✅ The Proxy Rule: Spring uses AOP proxies. External calls go through the proxy; internal calls don't. ✅ The Fix: Move the transactional logic to a separate Service or use AspectJ if complexity scales. ✅ Bonus: Always use readOnly = true for fetch operations to improve performance and avoid unnecessary flush calls. It’s not just about using the framework; it’s about understanding the "Magic" behind it. 🚀 Have you ever faced a "phantom" database bug because of this? Let's swap stories! 👇 hashtag #Java #SpringBoot #Backend #Database #CleanCode #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
-
When updating data in a Spring Boot API, standard validation can be too restrictive, often requiring all fields to be sent even for minor changes. A more flexible solution is to use @Validated with validation groups. This approach allows you to define separate sets of rules. For example, you can have a "create" group that requires all fields to be present, and a "default" group that only checks the format of fields that are actually provided in the request. In your controller, you then apply the appropriate rule set: the strict rules for creating new items and the flexible rules for updating them. This allows your API to handle both full and partial updates cleanly while reusing the same data object, resulting in more efficient code. #SpringBoot #Java #API #Validation #SoftwareDevelopment
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development