🔍 @Autowired vs @Inject vs @Resource in Spring In Spring, there are three annotations used for Dependency Injection: 1️⃣ @Autowired 2️⃣ @Inject 3️⃣ @Resource They all inject dependencies, but they come from different specifications and follow different rules. 1️⃣ @Autowired 📌 Provided by: Spring Framework 📌 Package: 'org.springframework.beans.factory.annotation.Autowired' Key Points ✔ Injects dependency by type ✔ Most commonly used in Spring ✔ Supports @Qualifier for resolving multiple beans Example @Autowired private UserService userService; If multiple beans exist: @Autowired @Qualifier("userServiceImpl") private UserService userService; 2️⃣ @Inject 📌 Provided by: Java Dependency Injection (JSR-330) 📌 Package: 'javax.inject.Inject' Key Points ✔ Works similar to @Autowired ✔ Injects dependency by type ✔ Framework independent (not only Spring) Example @Inject private UserService userService; If multiple beans exist: @Inject @Named("userServiceImpl") private UserService userService; 3️⃣ @Resource 📌 Provided by: Java EE (JSR-250) 📌 Package: javax.annotation.Resource Key Points ✔ Injects dependency by name first ✔ If name not found → fallback to type Example @Resource private UserService userService; Or explicitly: @Resource(name = "userServiceImpl") private UserService userService; 🧠 Simple Way to Remember @Autowired → Spring style injection @Inject → Java standard DI @Resource → Name-based injection #SpringBoot #SpringFramework #Java #DependencyInjection #BackendDevelopment
Spring Dependency Injection: Autowired, Inject, Resource
More Relevant Posts
-
🚀 Spring Framework 🌱 | Day 3 – Spring Bean Lifecycle – Step by Step Flow 1️⃣ Container Starts The Spring container starts and reads configuration. Example sources: XML configuration Java Config Annotations (@Component, @Bean) 2️⃣ Bean Instantiation Spring creates the bean object. Example: UserService userService = new UserService(); 3️⃣ Dependency Injection Spring injects required dependencies. Example: @Autowired PaymentService paymentService; Spring sets properties and constructor dependencies. 4️⃣ Aware Interfaces (Optional) If the bean implements Aware interfaces, Spring provides container details. Examples: BeanNameAware ApplicationContextAware BeanFactoryAware 5️⃣ BeanPostProcessor (Before Initialization) Spring runs BeanPostProcessor before initialization. Method: postProcessBeforeInitialization() Used for custom processing. 6️⃣ Initialization Spring runs initialization methods. Possible ways: @PostConstruct afterPropertiesSet() (InitializingBean) custom init-method 7️⃣ BeanPostProcessor (After Initialization) Spring runs: postProcessAfterInitialization() Here frameworks often create proxies (AOP). 8️⃣ Bean Ready to Use Now the bean is fully initialized and available for use in the application. 9️⃣ Bean Destruction (Shutdown) When the container stops: Spring calls destruction methods. Examples: @PreDestroy destroy() (DisposableBean) custom destroy-method Simple Flow Diagram Container Start ↓ Bean Instantiation ↓ Dependency Injection ↓ Aware Interfaces ↓ BeanPostProcessor (Before Init) ↓ Initialization ↓ BeanPostProcessor (After Init) ↓ Bean Ready to Use ↓ Bean Destroyed ✅ Short Interview Answer > In Spring, the IoC container manages the bean lifecycle. It starts with bean instantiation, performs dependency injection, executes aware interfaces, calls BeanPostProcessor before and after initialization, runs initialization methods, makes the bean ready for use, and finally calls destruction methods when the container shuts down. #SpringFramework #Java #BackendDevelopment #InterviewPreparation #Learning #Developers #SpringBoot
To view or add a comment, sign in
-
-
Spring Bean Lifecycle – Step by Step Flow 1️⃣ Container Starts The Spring container starts and reads configuration. Example sources: XML configuration Java Config Annotations (@Component, @Bean) 2️⃣ Bean Instantiation Spring creates the bean object. Example: UserService userService = new UserService(); 3️⃣ Dependency Injection Spring injects required dependencies. Example: @Autowired PaymentService paymentService; Spring sets properties and constructor dependencies. 4️⃣ Aware Interfaces (Optional) If the bean implements Aware interfaces, Spring provides container details. Examples: BeanNameAware ApplicationContextAware BeanFactoryAware 5️⃣ BeanPostProcessor (Before Initialization) Spring runs BeanPostProcessor before initialization. Method: postProcessBeforeInitialization() Used for custom processing. 6️⃣ Initialization Spring runs initialization methods. Possible ways: @PostConstruct afterPropertiesSet() (InitializingBean) custom init-method 7️⃣ BeanPostProcessor (After Initialization) Spring runs: postProcessAfterInitialization() Here frameworks often create proxies (AOP). 8️⃣ Bean Ready to Use Now the bean is fully initialized and available for use in the application. 9️⃣ Bean Destruction (Shutdown) When the container stops: Spring calls destruction methods. Examples: @PreDestroy destroy() (DisposableBean) custom destroy-method Simple Flow Diagram Container Start ↓ Bean Instantiation ↓ Dependency Injection ↓ Aware Interfaces ↓ BeanPostProcessor (Before Init) ↓ Initialization ↓ BeanPostProcessor (After Init) ↓ Bean Ready to Use ↓ Bean Destroyed ✅ Short Interview Answer > In Spring, the IoC container manages the bean lifecycle. It starts with bean instantiation, performs dependency injection, executes aware interfaces, calls BeanPostProcessor before and after initialization, runs initialization methods, makes the bean ready for use, and finally calls destruction methods when the container shuts down. #SpringFramework #Java #BackendDevelopment #InterviewPreparation #Learning #Developers #SpringBoot
To view or add a comment, sign in
-
-
Java 8 came out over 10 years ago. And it still breaks interviews in 2026. Here are the 8 features that changed everything (and what they actually replaced): → 1. Lambda Expressions Before: 10 lines of anonymous class boilerplate. After: (a, b) -> a.compareTo(b) One line. Same result. No excuses. → 2. Stream API Stop writing for-loops to filter lists. list.stream().filter().map().collect() reads like English. Your future self will thank you. → 3. Optional NullPointerException is the most common Java error in production. Optional.ofNullable() forces you to handle the null case explicitly. This alone will save you hours of debugging. → 4. Functional Interfaces Predicate. Function. Consumer. Supplier. 4 interfaces that make your code composable, testable, and clean. → 5. Method References names.forEach(System.out::println) Instead of: names.forEach(n -> System.out.println(n)) Small change. Huge readability boost. → 6. Default Methods in Interfaces You can now add new methods to interfaces without breaking every class that implements them. This is how Java evolved the Collections API without breaking your code. → 7. New Date/Time API LocalDate. LocalTime. ZonedDateTime. Finally — date handling that is immutable, thread-safe, and actually makes sense. RIP java.util.Date. → 8. Collectors API groupingBy(). joining(). partitioningBy(). Turn raw lists into maps, strings, and partitions — in one line. Java 8 wasn't just an update. It was a shift in how we think about writing Java. From imperative → declarative. From verbose → expressive. From fragile → safe. If you're still on Java 7 patterns in a Java 17+ codebase — this is your sign. Which of these 8 features do you use the most? Drop it in the comments 👇 #Java #Java8 #SoftwareEngineering #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Java Stream API – Writing Cleaner and More Powerful Code Before Java 8, developers mostly used loops to process collections. While loops work well, they can make code longer and harder to read when performing multiple operations. With Stream API, Java introduced a functional programming style that makes data processing cleaner, more readable, and more expressive. Let’s look at a simple example 👇 🔹 Without Stream API List<Integer> numbers = Arrays.asList(1,2,3,4,5,6); for(Integer n : numbers){ if(n % 2 == 0){ System.out.println(n); } } 🔹 With Stream API List<Integer> numbers = Arrays.asList(1,2,3,4,5,6); numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); Much cleaner and easier to understand. 💡 Key Features of Stream API ✔ Processes collections in a functional style ✔ Reduces boilerplate code ✔ Supports operations like "filter", "map", "sorted", "reduce" ✔ Allows easy parallel processing Example with "map": List<String> names = Arrays.asList("java","spring","hibernate"); names.stream() .map(String::toUpperCase) .forEach(System.out::println); Output: JAVA SPRING HIBERNATE Streams don’t store data, they process data from collections. Understanding Stream API helps developers write more expressive and maintainable Java code. #Java #Java8 #StreamAPI #Programming #SoftwareDevelopment #JavaDeveloper
To view or add a comment, sign in
-
-
💥 Every Java developer has met this villain at least once: NullPointerException In Java, if a variable is null and we try to use it, the program crashes. Example: Integer totalPrice = null; System.out.println(totalPrice + 100); // 💣 Crash This throws a NullPointerException. 🟢 What Spring is Introducing Spring Boot and Spring Framework are adopting JSpecify to improve null-safety in Java. 🔹 @NullMarked Means: By default, everything cannot be null Example: @NullMarked class OrderService { } Inside this class, parameters and return values are assumed NOT NULL unless specified. 🔹 @Nullable Means: This value may be null Example: public @Nullable Integer getDiscount(Order order) { return order.discount(); } This tells developers and tools: ⚠️ discount might be null 🔵 What Happens in the Code Example Integer discount = service.getDiscount(order); System.out.println(discount + 10); Problem: • getDiscount() is marked @Nullable • So discount might be null IDE will warn us: ⚠️ Possible NullPointerException So we must handle it: Integer discount = service.getDiscount(order); if (discount != null) { System.out.println(discount + 10); } 🟡 Why This Is Powerful Tools like NullAway or modern IDEs can now: ✅ Detect null problems before running the program ✅ Warn during compile time ✅ Make APIs clearer and safer 🔵 Simple Analogy Think of it like this: Old Java: method() -> maybe null, maybe not 🤷 New Spring + JSpecify: method() -> definitely NOT null ✅ method() -> maybe null ⚠️ Everything becomes explicit. 🟤 Real Benefit Before: 💥 Crash in production After: ⚠️ IDE warning before running the code 💡 Quick Note: Spring Boot 4 + JSpecify help Java detect NullPointerExceptions during compilation instead of runtime, making applications safer and code more reliable. 🚀 #Java #SpringBoot #BackendDevelopment #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
🔍 Java Reflection API — Powerful Yet Dangerous Have you ever wondered how frameworks like Spring or Hibernate inspect your classes at runtime? 👉 The answer lies in the Reflection API. 💡 What is Reflection? Reflection is a feature in Java that allows a program to inspect and manipulate classes, methods, and fields at runtime, even if they are private. --- ⚙️ What can you do with Reflection? ✔️ Access private fields and methods ✔️ Invoke methods dynamically ✔️ Create objects at runtime ✔️ Analyze class metadata (annotations, constructors, etc.) --- 🧠 Example: import java.lang.reflect.Method; class Test { private void message() { System.out.println("Hello from private method!"); } } public class Main { public static void main(String[] args) throws Exception { Test obj = new Test(); Method m = Test.class.getDeclaredMethod("message"); m.setAccessible(true); // bypass private access m.invoke(obj); } } --- ⚠️ Why “Dangerous”? ❗ Breaks encapsulation ❗ Slower than normal method calls ❗ Can introduce security vulnerabilities --- 🚀 Where is it used? 👉 Spring Framework 👉 Hibernate 👉 JUnit 👉 Dependency Injection & Annotations processing --- 💭 Use Reflection wisely — it gives you superpowers, but with responsibility. #Java #ReflectionAPI #Programming #BackendDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
When a controller returns a Java object… how does it become JSON in the API response?” Let’s understand this simply. Imagine this controller: @GetMapping("/task") public Task getTask() { return new Task(1, "Buy groceries"); } Here, we return a Java object. But in Postman, we see: { "id": 1, "title": "Buy groceries" } So… how did Java become JSON? 👉 Spring Boot uses Jackson Jackson is a library that converts: ✅ Java Object → JSON ✅ JSON → Java Object 🔹 What Happens Internally? 1️⃣ Controller returns a Java object 2️⃣ Spring Boot intercepts the response 3️⃣ Jackson converts it into JSON 4️⃣ Client receives JSON This process is called: 📌 Serialization (Java → JSON) 🔹 Reverse Also Happens When client sends JSON: { "title": "Buy groceries" } Spring converts it into a Java object automatically. 📌 Deserialization (JSON → Java) 🔹 Important Annotations ✅ @RestController → returns JSON ✅ @RequestBody → converts JSON → Java Example: @PostMapping("/task") public Task createTask(@RequestBody Task task) { return task; } 📌 In short: Java → JSON = Serialization JSON → Java = Deserialization And Spring Boot handles all of this using Jackson. 💡 Key Insight You don’t manually convert Java to JSON. Spring Boot does it automatically. That’s why building REST APIs feels so simple. What backend concept confused you the most when you started? 👇 Let’s discuss in comments #SpringBoot #Java #BackendDevelopment #RESTAPI #JavaDeveloper #Programming #SoftwareEngineering #LearnToCode
To view or add a comment, sign in
-
-
🚀 How does a Java object become JSON in a Spring Boot API ? Let’s understand this simply 👇 🔹 Example @GetMapping("/users") public User getUser() { return new User(1, "Ansar"); } 👉 In your code, you return a Java object 👉 But in Postman, you see: { "id": 1, "name": "Ansar" } So what happened behind the scenes? 🤔 🔹 The Magic Behind It Spring Boot uses a library called Jackson to handle this conversion automatically. ✔️ Java Object → JSON ✔️ JSON → Java Object 🔹 What Happens Internally? 1️⃣ Controller returns a Java object 2️⃣ Spring Boot intercepts the response 3️⃣ Jackson converts it into JSON 4️⃣ Client receives JSON 📌 This process is called Serialization (Java → JSON) 🔹 Reverse Process (Important) When a client sends JSON: { "name": "Ansar" } Spring Boot converts it into a Java object automatically. 📌 This is called Deserialization (JSON → Java) 🔹 Key Annotations ✔️ @RestController → returns JSON response ✔️ @RequestBody → converts JSON to Java object Example: @PostMapping("/user") public User createUser(@RequestBody User user) { return user; } 📌 Final Takeaway Java → JSON = Serialization JSON → Java = Deserialization All handled automatically by Spring Boot using Jackson 💡 Note: You don’t need to manually convert Java objects to JSON Spring Boot does it for you, making REST API development fast and efficient. #SpringBoot #Java #BackendDevelopment #RESTAPI #SoftwareEngineering #Learning #Developers
To view or add a comment, sign in
-
-
🚀 How does a Java object become JSON in a Spring Boot API ? Let’s understand this simply 👇 🔹 Example @GetMapping("/users") public User getUser() { return new User(1, "Ansar"); } 👉 In your code, you return a Java object 👉 But in Postman, you see: { "id": 1, "name": "Ansar" } So what happened behind the scenes? 🤔 🔹 The Magic Behind It Spring Boot uses a library called Jackson to handle this conversion automatically. ✔️ Java Object → JSON ✔️ JSON → Java Object 🔹 What Happens Internally? 1️⃣ Controller returns a Java object 2️⃣ Spring Boot intercepts the response 3️⃣ Jackson converts it into JSON 4️⃣ Client receives JSON 📌 This process is called Serialization (Java → JSON) 🔹 Reverse Process (Important) When a client sends JSON: { "name": "Ansar" } Spring Boot converts it into a Java object automatically. 📌 This is called Deserialization (JSON → Java) 🔹 Key Annotations ✔️ @RestController → returns JSON response ✔️ @RequestBody → converts JSON to Java object Example: @PostMapping("/user") public User createUser(@RequestBody User user) { return user; } 📌 Final Takeaway Java → JSON = Serialization JSON → Java = Deserialization All handled automatically by Spring Boot using Jackson 💡 Note: You don’t need to manually convert Java objects to JSON Spring Boot does it for you, making REST API development fast and efficient. #SpringBoot #Java #BackendDevelopment #RESTAPI #SoftwareEngineering #Learning #Developers
To view or add a comment, sign in
-
-
Built DTOForge, a small Spring Boot tool that generates Java DTOs from JSON. Useful when integrating external APIs and you do not want to keep writing DTOs by hand. Supports: * Java records * Java classes * nested objects * arrays * optional Jackson annotations Source: `https://lnkd.in/eWEpUxPY Medium article: https://lnkd.in/eDmK-eVx #Java #SpringBoot #OpenSource #BackendDevelopment #APIIntegration
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