Saturday, 14 June 2025

Spring framework

 

1. What is IoC (Inversion of Control) or Dependency Injection?

Inversion of Control (IoC) is a design principle where control of object creation and binding is shifted from the application code to a container/framework. In Dependency Injection (DI), this is done by externally injecting dependencies (objects) into a class rather than the class creating them itself.

  • Example: Instead of new Service(), you declare a Service field and let the Spring container inject the instance.

  • Benefits:

    • Decouples class dependencies.

    • Improves maintainability and testability.

What is Dependency Injection (DI)?

Dependency Injection is a specific implementation technique of IoC. It is a pattern where dependencies (objects that a class needs to perform its work) are "injected" into the class, instead of the class creating them directly.

Think of IoC as the general concept, and DI as one of the ways to achieve it.

Types of Dependency Injection in Spring:

  1. Constructor Injection

  2. Setter Injection

  3. Field Injection (not recommended for testing)


Example Without DI (Tight Coupling):

public class StudentService { private StudentRepository repository = new StudentRepository(); // tightly coupled public void register() { repository.save(); } }
  • The StudentService class creates the StudentRepository on its own using new.

  • Hard to test and maintain.


Same Example With DI (Loose Coupling using IoC):

Step 1: Define the Repository

@Repository public class StudentRepository { public void save() { System.out.println("Student saved!"); } }

Step 2: Inject the Repository into the Service

@Component public class StudentService { private final StudentRepository repository; @Autowired public StudentService(StudentRepository repository) { this.repository = repository; } public void register() { repository.save(); } }
  • Here, StudentRepository is injected by the Spring IoC container.

  • The class does not manage the creation of its dependency.


Spring Boot Main Class

@SpringBootApplication public class MyApp { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(MyApp.class, args); StudentService service = context.getBean(StudentService.class); service.register(); } }

✅2. Types of Dependency Injection

Spring supports:

  • Constructor Injection

  • Setter Injection

Other frameworks (like Avalon) also support Interface Injection, but Spring does not.

a. Constructor Injection

@Component public class BookService { private final BookRepository repository; @Autowired public BookService(BookRepository repository) { this.repository = repository; } }

b. Setter Injection

@Component public class BookService { private BookRepository repository; @Autowired public void setBookRepository(BookRepository repository) { this.repository = repository; } }

3. Benefits of IoC (Dependency Injection)

  • Less boilerplate code: We don’t need to write factory or singleton code to manage dependencies.

  • Improved testability: Dependencies can be easily mocked.

  • Loose Coupling: Components are independent of how their dependencies are constructed.

  • Lifecycle and scope control: Spring manages object scopes (singleton, prototype, etc.).

  • Support for AOP: Cross-cutting concerns like logging, security can be injected.


4. What is Spring Framework?

Spring is a lightweight, open-source Java framework for building enterprise-grade applications. It provides a comprehensive infrastructure support for developing Java applications.

Advantages:

  • Modular & Layered Architecture.

  • Promotes Plain Old Java Object (POJO) programming.

  • Reduces boilerplate code through IoC/DI.

  • Open-source and vendor-neutral.


5. Features of Spring

FeatureDescription
LightweightMinimal memory and processing overhead.
IoCDependencies are injected into components.
AOP (Aspect-Oriented Programming)Separates cross-cutting concerns like logging/security.
ContainerManages object lifecycle and configuration.
Spring MVCPowerful and extensible web MVC framework.
Transaction ManagementAbstracts transactions across databases and APIs.
JDBC Exception HandlingSimplifies JDBC error handling via custom exception hierarchy.
ORM IntegrationSeamlessly integrates with Hibernate, JPA, etc.

6. Spring MVC Example

@Controller
public class GreetingController { @GetMapping("/greet") public String greet(Model model) { model.addAttribute("message", "Hello from Spring MVC!"); return "greeting"; // returns greeting.jsp or other view } }

7. JDBC Exception Handling

Spring provides a cleaner way of dealing with exceptions:

@Repository
public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public void addUser(User user) { try { jdbcTemplate.update("INSERT INTO users(name) VALUES (?)", user.getName()); } catch (DataAccessException e) { // Handle Spring’s wrapped exception instead of raw SQLException throw new RuntimeException("Database error: " + e.getMessage()); } } }

8. Types of Dependency Injection Spring Supports

  • Constructor Injection: Preferred when dependencies are mandatory.

  • Setter Injection: Preferred when dependencies are optional.

Example of Constructor Injection:

@Service public class OrderService { private final OrderRepository repository; @Autowired public OrderService(OrderRepository repository) { this.repository = repository; } }

Example of Setter Injection:

@Service public class OrderService { private OrderRepository repository; @Autowired public void setRepository(OrderRepository repository) { this.repository = repository; } }

9. What is BeanFactory?

BeanFactory is the simplest Spring IoC container. It lazily loads beans and manages their lifecycle.

Core Interfaces:

  • BeanFactory is the root interface.

  • Implemented by classes like XmlBeanFactory.

Why prefer ApplicationContext?

  • Supports internationalization (i18n)

  • Publishes events to listeners

  • Resolves file resources

  • Autowires annotations like @Autowired, @Component

Example:

BeanFactory factory = new XmlBeanFactory(new ClassPathResource("beans.xml")); Student student = (Student) factory.getBean("student");

10.What is the difference between BeanFactory and ApplicationContext?

BeanFactory and ApplicationContext are Spring IoC containers responsible for managing beans. However, ApplicationContext provides a more advanced and feature-rich implementation compared to BeanFactory.

Key Differences:

  1. Message Resolution (i18n): ApplicationContext provides an internationalization (i18n) mechanism to resolve text messages using properties files, which BeanFactory does not.
  2. Resource Loading: It supports a generic way to access file resources like images, properties files, etc., using the Resource interface. For example, loading file:/some/path/file.txt or classpath:config.xml.
  3. Event Propagation: ApplicationContext can publish application events to beans registered as ApplicationListener. This is part of the observer pattern for event-driven apps.
  4. Declarative Operations: You can handle things like autowiring, property injection, and lifecycle callbacks declaratively (via XML or annotations) in ApplicationContext. These must be manually handled in BeanFactory.
  5. Built-in Support for BeanPostProcessors and BeanFactoryPostProcessors: These are automatically detected and registered in ApplicationContext but require manual registration in BeanFactory.
  6. Interfaces Implemented:
    • ApplicationContext implements ResourceLoader, MessageSource, ApplicationEventPublisher, and BeanFactory.
    • BeanFactory is a basic container providing only getBean() and dependency resolution.

11. What are the common implementations of the ApplicationContext?
Spring provides several implementations of ApplicationContext, used depending on the environment: 1. ClassPathXmlApplicationContext: o Loads configuration XML from the classpath. o Common in standalone apps. Example: ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
2. FileSystemXmlApplicationContext: o Loads the context definition from an XML file in the file system. o Useful when the config is outside the classpath. Example: ApplicationContext context = new FileSystemXmlApplicationContext("C:/config/beans.xml");
3. XmlWebApplicationContext: o Specialized for web applications. o Automatically initialized by the Spring Web module (via ContextLoaderListener). ________________________________________ 12. How does a typical Spring implementation look like? A complete Spring application typically includes: 1. Interface: Defines the contract for the service. 2. Implementation Class: Implements the interface, uses Spring DI for its dependencies. 3. Spring AOP (optional): Adds cross-cutting concerns like logging, security, or transactions. 4. Configuration File (XML or Java): Defines the beans, wiring, scopes, etc. 5. Client Code: Retrieves the bean from Spring and calls the required methods. ________________________________________ 13. What is the typical bean lifecycle in Spring BeanFactory Container? The following steps describe how Spring manages the bean lifecycle: 1. Bean Instantiation: Bean definitions are read from XML or Java config and objects are instantiated. 2. Dependency Injection: All defined properties (via setters or constructor) are injected. 3. BeanNameAware: If implemented, Spring calls setBeanName() with the bean’s ID. 4. BeanFactoryAware: If implemented, Spring injects the BeanFactory into the bean. 5. BeanPostProcessor (Before): Any registered BeanPostProcessor's postProcessBeforeInitialization() method is called. 6. Custom init-method: If configured, Spring calls the custom init method (defined using init-method). 7. BeanPostProcessor (After): Calls postProcessAfterInitialization() from BeanPostProcessor. ________________________________________ 14. What do you mean by Bean wiring? Bean wiring is the process of defining how beans are connected or injected with dependencies in the Spring container. Autowiring Modes: 1. no (default): No autowiring; dependencies must be explicitly defined. 2. byName: Spring injects a bean whose name matches the property name. 3. byType: Spring injects a bean whose type matches the property type. 4. constructor: Uses the constructor with matching arguments. 5. autodetect (deprecated): Chooses between constructor and byType using reflection. ________________________________________ 15. What ORM frameworks does Spring support? Spring supports integration with multiple ORM frameworks: • Hibernate • iBatis / MyBatis • JPA (Java Persistence API) • TopLink (now EclipseLink) • JDO (Java Data Objects) • OJB (ObJectRelationalBridge) ________________________________________ 16. What are the ways to access Hibernate using Spring? Two common approaches: 1. Using HibernateTemplate and Callback API: o Simplifies repetitive boilerplate Hibernate code (session management, transactions). o E.g., hibernateTemplate.save(entity); 2. Extending HibernateDaoSupport: o Inherit this class to gain access to HibernateTemplate and use methods directly. 3. With AOP-based Transaction Management: o Declarative transactions using Spring’s @Transactional. ________________________________________ 17. How to integrate Spring and Hibernate using HibernateDaoSupport? Steps: 1. Configure LocalSessionFactoryBean in Spring: Inject database properties, mapping files, etc. 2. DAO Implementation Extends HibernateDaoSupport: This gives access to getHibernateTemplate() for CRUD operations. 3. Wire Transaction Support using AOP: Use XML or @Transactional to define transaction boundaries. ________________________________________ 18. What are the Bean Scopes in Spring Framework? Scope Description singleton Single instance per Spring container. Shared and reused. (Default) prototype A new instance is created every time it is requested. request One instance per HTTP request. Only available in web applications. session One instance per HTTP session. Used in web applications. globalSession Like session but shared across all portlets in a web app (Portlet context only). ________________________________________ 19. What is AOP (Aspect-Oriented Programming)? AOP is a programming paradigm that allows separation of cross-cutting concerns (like logging, security, and transaction management) from core business logic. • Aspect: Module for cross-cutting concern. • Join Point: Specific point in execution (e.g., method execution). • Advice: Code to execute at a join point (before, after, around). ________________________________________ 20. How is AOP used in Spring? Spring uses AOP to provide declarative enterprise services, such as: • Transaction Management (@Transactional) • Security (@PreAuthorize) • Logging, Auditing, etc. Developers can also define custom aspects using @Aspect. ________________________________________ 21. What is an Aspect? An aspect is a module that encapsulates behaviors that cut across multiple classes. Examples: • Logging aspect • Security aspect • Transaction aspect Spring supports two types: • XML-based AOP • Annotation-based (@Aspect) ________________________________________ 22. What is a JoinPoint? A join point is a specific point during program execution, such as: • Method execution • Exception handling • Constructor invocation Spring AOP supports only method execution join points. ________________________________________ 23. What is Advice? Advice is the actual action taken at a join point. Types include: • Before Advice: Runs before the method. • After Advice: Runs after the method completes. • After Returning: Runs if method completes successfully. • After Throwing: Runs if method throws an exception. • Around Advice: Surrounds the method call, giving full control. In Spring, advice is implemented as methods inside an aspect class.

24. ✅ RestTemplate in Java (Spring Framework)
RestTemplate is a synchronous HTTP client provided by Spring for consuming RESTful web services. It's part of the spring-web module. 📌 Note: As of Spring 5, RestTemplate is in maintenance mode. It is still widely used, but WebClient (from Spring WebFlux) is now the recommended alternative for new applications due to its non-blocking nature. 🔹 When to use RestTemplate: Use it when: You want to make HTTP requests (GET, POST, PUT, DELETE, etc.) The communication is synchronous (blocking). You are consuming REST APIs in a Spring Boot or Spring MVC application. 🔧 Add Maven Dependency xml <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> 🛠️ How to Create a RestTemplate Bean java @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } Or use directly: java RestTemplate restTemplate = new RestTemplate(); 📤 Common HTTP Methods with Examples 1. GET Request java String url = "https://jsonplaceholder.typicode.com/posts/1"; Post post = restTemplate.getForObject(url, Post.class);
2. POST Request java Post newPost = new Post("Title", "Body", 1); Post createdPost = restTemplate.postForObject( "https://jsonplaceholder.typicode.com/posts", newPost, Post.class );
3. PUT Request java Post updatedPost = new Post("Updated Title", "Updated Body", 1); restTemplate.put("https://jsonplaceholder.typicode.com/posts/1", updatedPost);
4. DELETE Request java restTemplate.delete("https://jsonplaceholder.typicode.com/posts/1");
5. Exchange with Headers java HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer your_token_here"); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange( "https://api.example.com/data", HttpMethod.GET, entity, String.class ); 📦 Example POJO java public class Post { private Integer id; private String title; private String body; private Integer userId; // Getters and setters // Constructor } ⚠️ Deprecation Note RestTemplate is still safe to use for simple apps. For asynchronous or reactive apps, prefer using: WebClient (Spring WebFlux)