?? Day 7: My Spring Boot Learning Journey ??

?? Day 7: My Spring Boot Learning Journey ??

Today, I explored some critical concepts that make Spring Boot applications flexible and efficient. Here's what I learned:

1?? Spring Boot Packaging

In the J2EE application, modules are packed as JAR, WAR, and EAR. It is the compressed file formats that is used in the J2EE. J2EE defines three types of archives:

  • WAR
  • JAR
  • EAR


WAR

  • WAR stands for Web Archive. WAR file represents the web application.
  • Web module contains servlet classes, JSP files, HTML files, JavaScripts, etc. are packaged as a JAR file with .war extension. It contains a special directory called WEB-INF.
  • WAR is a module that loads into a web container of the Java Application Server. The Java Application Server has two containers: Web Container and EJB Container.
  • The Web Container hosts the web applications based on Servlet API and JSP. The web container requires the web module to be packaged as a WAR file. It is a WAR file special JAR file that contains a web.xmlv file in the WEB-INF folder.
  • An EJB Container hosts Enterprise Java beans based on EJB API. It requires EJB modules to be packaged as a JAR file. It contains an ejb-jar.xml file in the META-INF folder.
  • The advantage of the WAR file is that it can be deployed easily on the client machine in a Web server environment. To execute a WAR file, a Web server or Web container is required. For example, Tomcat, Weblogic, and Websphere.

JAR

  • JAR stands for Java Archive. An EJB (Enterprise Java Beans) module that contains bean files (class files), a manifest, and EJB deployment descriptor (XML file) are packaged as JAR files with the extension .jar.
  • It is used by software developers to distribute Java classes and various metadata.
  • In other words, A file that encapsulates one or more Java classes, a manifest, and descriptor is called JAR file. It is the lowest level of the archive. It is used in J2EE for packaging EJB and client-side Java Applications. It makes the deployment easy.

EAR

  • EAR stands for Enterprise Archive. EAR file represents the enterprise application. The above two files are packaged as a JAR file with the .ear extension.
  • It is deployed into the Application Server. It can contain multiple EJB modules (JAR) and Web modules (WAR). It is a special JAR that contains an application.xml file in the META-INF folder.

Spring Boot Auto-configuration

  • Spring Boot’s auto-configuration is a feature that automatically configures the Spring application based on the dependencies present in the classpath.
  • It aims to simplify the configuration process and reduce the need for boilerplate code.
  • Auto-configuration is achieved through the use of conditional configuration classes, which are conditionally loaded based on the presence or absence of certain classes or properties.

Here’s a brief explanation of how Spring Boot auto-configuration works:

  1. Classpath scanning: Spring Boot scans the classpath for specific libraries or classes associated with various functionalities, such as databases, messaging systems, web servers, etc.
  2. Conditional checks: Auto-configuration classes include conditions that check whether certain conditions are met. If the conditions are satisfied, the configuration is applied. If not, the configuration is skipped.
  3. Application properties: Configuration can be further customized using application.properties or application.yml files. Properties specified in these files can influence the auto-configuration process.

Here’s a simple example to illustrate auto-configuration in Spring Boot:


In this example:

  • @SpringBootApplication is a meta-annotation that includes several other annotations, including @EnableAutoConfiguration.
  • @EnableAutoConfiguration enables Spring Boot’s auto-configuration feature.

Let’s say you have added the Spring Data JPA dependency to your project. Spring Boot will automatically configure a data source and an entity manager for you, assuming it finds the necessary classes on the classpath. If you want to customise this behaviour, you can provide your own configuration by defining a DataSource bean,

For Example: -

  • In this configuration class, you are providing your own DataSource bean. The @ConfigurationProperties annotation allows you to bind properties from the application.properties or application.yml file to this bean.
  • This is a simple example, but Spring Boot’s auto-configuration becomes more powerful as your project grows, handling more complex configurations based on the dependencies you include.
  • In Spring Boot, you can disable specific auto-configurations or configuration classes by using the @SpringBootApplication annotation with the exclude attribute. This attribute allows you to specify the classes or packages to be excluded from auto-configuration.

Here are two ways to disable specific configurations:

  1. Disabling Auto-Configuration Classes:

In this example, SomeAutoConfiguration.class is the class you want to exclude from auto-configuration.

.

2. Disabling Auto-Configuration Using Properties:

  • You can also use application properties to disable specific auto-configurations. Specify the fully qualified name of the class or classes you want to exclude in your application.properties or application.yml file:

This property tells Spring Boot to exclude the specified auto-configuration class.

3. Using a Configuration Class to Disable Auto-Configuration:

  • Create a configuration class and use the @ConditionalOnProperty annotation to conditionally enable or disable certain configurations based on the presence or absence of a specific property.

In this example, the configuration will only be applied if the property myapp.some-feature.enabled is set to false. You can adjust the property name and value according to your needs.


3?? Spring Boot Auto-wiring & Its Advantages

  • Auto-wiring, also known as automatic wiring, is a feature of the Spring Framework that automatically wires beans together by matching the types of the properties, constructor arguments, or method arguments of the beans.
  • Auto-wiring eliminates the need for explicit configuration of the relationships between beans in the application context configuration file, thus reducing the amount of XML configuration and making the code more readable.

Auto-wiring can be applied to the following types of beans:

  • Properties: Spring can automatically set the properties of a bean by matching the type of the property with the beans available in the Application Context

Autowiring byType:
@Service
public class MyService {
    @Autowired
// it will find out MyRepository Type In Application Context
// then wire it to property .
    private MyRepository repository;
}

//Spring will automatically wire the MyRepository 
//bean to the repository property of the MyService bean by matching the types.        
Autowiring byName:

@Repository
@Primary // to indicate that it should be used as the primary candidate for autowiring, 
// in case multiple beans with the same name are present in the Application Context
@Qualifier("myRepositoryBean1")
public class MyRepository {
    public void save() {
        //Code to save data
    }
}

@Repository
@Qualifier("myRepositoryBean2")
public class MyRepository {
    public void save() {
        //Code to save data
    }
}


@Service
public class MyService {
    @Autowired
//spring ioc container find out bean with name myRepositoryBean1 and wire to this property of  MyService
    @Qualifier("myRepositoryBean1")
    private MyRepository repository;
}
        

  • Constructor arguments: Spring can automatically call the appropriate constructor by matching the constructor argument types with the beans available in the Application Context

Autowiring by constructor:
@Service
public class MyService {
    private MyRepository repository;
    
    @Autowired
//find out based on type and wiring will be done using constructor
    public MyService(MyRepository repository) {
        this.repository = repository;
    }
}

// this is based on byName using constructor

@Service
public class MyService {
    private MyRepository repository;
    
    @Autowired
//it will find bean By name and then wire
    public MyService(@Qualifier("myRepositoryBean1") MyRepository repository) {
        this.repository = repository;
    }
    public void doSomething() {
        repository.save();
    }
}        

Spring will automatically wire an instance of MyRepository to the constructor of MyService class.

  • Method arguments: Spring can automatically call the appropriate setter methods by matching the method argument types with the beans available in the Application Context.

Autowiring by setter methods
@Service
public class MyService {
    private MyRepository repository;
    

//Spring will automatically wire the MyRepository bean to the setRepository method of the MyService bean.
    @Autowired
    public void setRepository(MyRepository repository) {
        this.repository = repository;
    }
}


// --------
@Service
public class MyService {
    private MyRepository repository;
    @Autowired
    @Qualifier("myRepositoryBean1")
//wiring of bean using setter method with byName 
    public void setRepository(MyRepository repository) {
        this.repository = repository;
    }
    public void doSomething() {
        repository.save();
    }
}        

  • In this example, MyService class has a setter method that takes a MyRepository object as an argument.
  • The @Autowired annotation on the setter method and @Qualifier("myRepositoryBean1") annotation on the argument tells Spring to automatically wire an instance of MyRepository bean with the name "myRepositoryBean" to this setter method when creating an instance of MyService.

Autowiring in Spring Boot has several advantages, including:

Improved collaboration

  • Autowiring ensures that components are wired correctly and consistently across an application, which is important for large projects with multiple developers.

Integration with Spring Framework features

  • Autowiring integrates with other Spring Framework features, such as transactions, aspects, and security.

Less code

  • Autowiring requires less code because it automatically injects dependencies at runtime, instead of requiring the developer to write code to inject dependencies explicitly.

Reduces development time

  • Autowiring saves time by removing the need to specify constructor arguments and properties.?

Updates configuration

  • Autowiring can update configuration as objects evolve

Supports loose coupling

  • Autowiring supports loose coupling, which is a key software engineering principle. This allows classes to remain independent of each other, which can lead to more modular and scalable code.

4?? Spring Expression Language (SpEL)

  • Spring Expression Language (SpEL) is a language that allows users to query and manipulate object graphs at runtime in Spring Boot:?

Features

  • SpEL supports a variety of features, including method invocation, string templating, and dynamic value assignment

Compatibility

  • SpEL can be used with both XML-based and annotation-based Spring configurations and bean definitions

Operators and functions

  • SpEL offers a range of operators and functions for performing operations on data, including arithmetic, comparison, logical, and ternary operators.

Expression templates

  • SpEL allows users to mix literal text with evaluation blocks, which are delimited by prefix and suffix characters.?

EvaluationContext

The EvaluationContext interface is used to evaluate expressions and resolve properties, methods, and fields.?

SpEL was created to provide a single, well-supported expression language for the Spring portfolio. It's based on a technology-agnostic API that allows other expression language implementations to be integrated.?


5?? Spring Boot Event Handling

Event handling in Spring Boot is a mechanism that controls events and determines what to do when they occur:?

Architecture

  • Spring's event handling system uses the Observer pattern to create a loosely coupled architecture.
  • This reduces dependencies between components, making the codebase more maintainable and scalable.

Annotations

  • Spring provides the @EventListener annotation to handle events more concisely. This annotation allows any method in a managed bean to act as an event listener.?

Publish-subscribe pattern

  • Spring's publish-subscribe pattern allows for decoupled communication between event publishers and subscribers.
  • This enables efficient data transmission and independent updates to either component.

Examples

Here are some examples of event handling in Spring Boot:

  • Registration and email: When a new user is registered, the registration service triggers an event with the new user's information. The email service then consumes the event and sends an email to the user.?
  • Project creation: When a new project is created, a project created event is published by ApplicationEventPublisher. ApplicationListener listens to this event and updates the project-user mapping.?
  • TransactionNotificationEvent: This event holds all the details of a financial transaction, such as mobile numbers, account specifics, and transaction types. When a customer initiates a transaction, this event triggers a series of actions in the event-driven system.?

Sridhar Raj P

?? On a mission to teach 1 million students | Developer & Mentor | 5,500+ Students ??| JavaScript | React JS | Redux | Python | Java | Springboot | MySQL | Self-Learner | Problem Solver

1 个月

Interesting

要查看或添加评论,请登录

Sakthi Kumar M的更多文章

社区洞察

其他会员也浏览了