Generics in Java with Examples

Generics in Java with Examples

Generics allows us to pass the generic types as parameters to a class or methods.
Example: class A<T>

Generics Advantages:

  • Stronger type checking
  • Casting elimination

Type Parameter Naming Conventions:

  • E – Element
  • K – Key
  • V – Value
  • N – Number
  • T – Type

There are various ways of using Generics, In this post let us see, generics with

  • Upper Bounded Wildcards
  • Unbounded Wildcards
  • Lower Bounded Wildcards

First let us see an example of using generics along with the class

Output:

Now let us see another example of using Generics with Key and Value along with Upper Bound Wildcards, Unbounded Wildcard and Lower Bound Wildcards.

Wildcards usually starts with “?” – Example: List<? extends Number>

Upper Bound Wildcards
Used to relax restrictions on a variable. In the below example we have used upperBound wildcard to pass integers, calculate sum of it and change it double and print it.

Unbounded Wildcards:
Unbounded wildcards is used for unknown types. It can be of any type, Integer or String or object etc..

Lower Bound Wildcards:
Lower Bound Wildcards restricts the unknown type to be specific. (Upper Bound relaxes the restrictions)

 

 

Read More

SpringBoot – @Scheduled Annotation with Examples

SpringBoot – @Scheduler Annotation with Examples

In our applications we might need certain logic or method that needs to be executed at certain intervals. For ex: We might require a method to be executed every 15 min.

In SpringBoot we have an annotation to achieve this, @Scheduled annotation. From package –  org.springframework.scheduling.annotation.Scheduled.

@Scheduled types,

  • initialDelay
  • fixedRate
  • fixedDelay
  • fixedDelayString
  • cron

initialDelay:

  • The milliseconds delay before the execution of fixedRate or fixedDelay

fixedRate:

  • Invocation with specific period of time

fixedDelay:

  • Fixed period between the last invocation and the next invocation

fixedDelayString:

  • Same as fixedDelay but this accepts string parameter
  • Example: @Scheduled(fixedDelayString = “5000”)

Now for example, if we pass incorrect number as string to fixedDelayString what will happen?

Let us pass this,
@Scheduled(fixedDelayString = “5000r“)
When we try to run this, we will get an exception

org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘myApplication’: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid @Scheduled method ‘ScheduledFixedRate’: Invalid fixedDelayString value “5000r” – cannot parse into integer

Cron:

  • A cron-like expression which has 6 arguments – Minutes, Hour, Date, Month, Week and Year
  • It looks like @Scheduled(cron = “* * * * * *”)

Now let us see an detailed example,

In the above example we have scheduled a cron,

@Scheduled(cron = “10 02 21 * * *”) – This will execute exactly on 21:02:10 – 21 hours, 02 minutes 10 seconds

When the above code is executed,

 

 

 

Read More

SpringBoot – @ApplicationReadyEvent, @ApplicationFailedEvent and @ContextRefreshedEvent

SpringBoot – Executing method when  Application Starts and Periodically

When building an application, We might face an requirement that some tasks needs to be executed along with the application when the application Starts. Springboot has options available to make this happen.

@ApplicationReadyEvent
@ApplicationFailedEvent

What does these annotations do?
As the name suggests, when we use this annotation over a method, when the springboot application starts these methods will get executed along with the springboot startup.

When the application is fails on startup, ApplicationFailedEvent will get triggered.

@ContextRefreshedEvent
ContextRefreshedEvent annotation will also get executed when the springBoot application starts, But the difference between ApplicationReadyEvent and ContextRefreshedEvent is – ContextRefreshedEvent will get executed when ApplicationReadyEvent is getting intialized. So ContextRefreshedEvent will get executed even before ApplicationReadyEvent. (Refer here)

Now let us see an detailed example of using these annotations,

When we execute this code,


Now let us make an error to make the application fail, so ApplicationFailedEvent will get executed,

on executing the above code, it should throw ArithmeticException and ApplicationFailedEvent should get executed,

 

Read More

Spring Boot + Hibernate CRUD Example

Spring Boot + Hibernate CRUD Example

Let us see an example of spring boot + hibernate integration example with Crud (Create, Read, Update and Delete) operations.

In the below example we are going to use Spring jpa and CrudRepository.

Annotations used in the below example:

@EnableJpaRepositories: Used to enable JPA repositories.
@EnableTransactionManagement:  Used for enabling transaction management, similar to <tx>.

Crud Repository:
In the below example, we have used crud repository, let us understand about this repository. The CrudRepository provides CRUD functionality for the Entity class. It has in-build functions for performing CRUD operations which allow us to write less code and use the functions directly from this repository.

Now let us see an example of CRUD operations with Spring Boot and Hibernate. (You can Download the Code Here)

Structure:

pom.xml

application.properties:

com.javainfinite.model

com.javainfinite.EmployeeDAO

com.javainfinite.application.controller

com.javainfinite.application

 Saving Employee – First Record

Saving Employee – Second Record

Get all Employees – To List Entered Both Records

Get By Id:

Updating Record

After Update Getting By Id:

Deleting a Record:

 

After Deleting a Record

You can Download the Code Here – Please modify the database properties.

 

Read More

Simple SpringBoot RestAPI Example

Simple SpringBoot RestAPI Example:
Spring Boot is a way to create stand-alone applications with less or no configurations and has defaults for annotation configuration which we will use in our application.

In this example, Let us a see a very simple SpringBoot with one RESTAPI url. This example does not have any database connection or pojo classes.

Structure:

 

POM.xml

SpringController.java

SpringRest.java

Let us start the spring boot application,

 

Hitting the URL with PostMan,

 

Read More