Monday, December 28, 2020

Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

In Spring framework, by default all the singleton beans are eagerly created and configured by ApplicationContext as part of the initialization process. Though this behavior of pre-instantiation is desirable most of the time as you can detect errors in the configuration immediately. But sometimes you may have a large object graph and loading all those beans in the beginning itself may be expensive. In that kind of scenario you can prevent pre-instantiation of a singleton bean by configuring the Spring bean to be initialized lazily.

If you mark a bean as lazy-initialized in Spring that means IoC container will create a bean instance when it is first requested, rather than at startup.

Here note that when a lazy-initialized bean is a dependency of a singleton bean that is not lazy initialized, the ApplicationContext creates the lazy-initialized bean at startup, because it must satisfy the singleton’s dependencies.

Saturday, December 26, 2020

Injecting Inner Beans in Spring

This post shows how to inject inner beans in Spring and what are the scenarios when you would need to inject a bean as an inner bean.

Let’s say you have a Java class which refers to another class object and the access type for that object is private. In that case what do you think is the best way to provide bean definition in Spring. Let me provide class (Employee.java) here so you can understand what I am saying.

Friday, December 25, 2020

ServiceLocatorFactoryBean in Spring Framework

ServiceLocatorFactoryBean in Spring framework as the name suggests is an implementation of service locator design pattern and helps with locating the service at run time.

ServiceLocatorFactoryBean helps if you have more than one implementation of the same type and want to use the appropriate implementation at the run time i.e. you have an interface and more than one class implementing that interface and you want to have a factory that will return an appropriate object at run time.

registerShutdownHook() Method in Spring Framework

In the post Spring Bean Life Cycle we have already seen that you can provide destroy methods for your beans to do clean up. One problem is that these destroy callback methods are not executed automatically you do have to call AbstractApplicationContext.destroy or AbstractApplicationContext.close before shutting down the IOC container. There is another option to ensure graceful shutdown, you can register a shutdown hook with the JVM using registerShutdownHook() method in Spring.

Note that this problem is only with non-web applications. Spring’s web-based ApplicationContext implementations already have code in place to shut down the Spring IoC container gracefully when the relevant web application is shut down.

Thursday, December 24, 2020

Batch Processing in Java JDBC - Insert, Update Queries as a Batch

If you have a large number of similar queries it is better to process them in a batch rather than as individual queries. Processing them as a batch provides better performance as you send a group of queries in a single network communication rather than sending individual queries one by one.

Batch support in JDBC

JDBC provides batch support in the form of addBatch() and executeBatch() methods.

If you are using Statement interface then use addBatch(String Sql) method to add queries to the batch.

For PreparedStatement and CallableStatement use addBatch() method as parameters for the query are provided later.

Once you have added queries to a batch you can call executeBatch() method to execute the whole batch of queries.

DB you are using may not support batch updates. You should use the supportsBatchUpdates() method of the DatabaseMetaData interface to check whether the target database supports batch updates or not.

The method returns true if this database supports batch updates; false otherwise.

Wednesday, December 23, 2020

Transaction Management in Java-JDBC

This post provides detail about JDBC transaction management with examples for starting a transaction in JDBC, committing and rolling back a transaction, setting savepoint for transaction rollback.


DataSource in Java-JDBC

In the examples given in the previous post Java JDBC Steps to Connect to DB we have seen how to get a connection using DriverManager class. That’s ok for sample code where you just need to test using a connection and close it. But in a real life application creating connection object every time DB interaction is needed will be very time consuming. What you need is a connection pool where a given number of connection objects are created in the beginning itself and are reused.

In this post we’ll see another way of connecting to DB from your Java application using a DataSource object which provides the connection pooling. There are other advantages of using DataSource in JDBC too.

Tuesday, December 22, 2020

Java Lambda Expression as Method Parameter

As we have already seen in the post about functional interface that lambda expression provides implementation for the abstract method present in the functional interface and the target type for the lambda expression is the functional interface. In the simple terms we can say that lambda expression is an object that can be used where ever the reference of functional interface is required. One of these uses is passing lambda expression as an argument. To pass a lambda expression as a method parameter in Java, the type of the method argument, which receives the lambda expression as a parameter, must be of functional interface type.

Java Lambda Expressions Interview Questions And Answers

In this post some of the Java Lambda Expressions interview questions and answers are listed. This compilation will help the Java developers in preparing for their interviews especially when asked interview questions about Java 8.

  1. What is lambda expression?

    Lambda expression in itself is an anonymous method i.e. a method with no name which is used to provide implementation of the method defined by a functional interface.

    A new syntax and operator has been introduced in Java for Lambda expressions.

    General form of lambda expression

    (optional) (Arguments) -> body
    

Monday, December 21, 2020

Connection Pooling Using Apache DBCP in Java

In this post we’ll see how to configure connection pooling in your Java application using Apache DBCP datasource. The DB we are connecting to is MySQL.

Jars needed

If you are using Maven then you can add the following dependency.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.8.0</version>
</dependency>

Connection Pooling Using C3P0 in Java

In this post we’ll see how to configure connection pooling using C3P0 datasource in your Java application. The DB we are connecting to is MySQL.

Jars needed for C3P0

You need the following jars in your project’s classpath, check the versions as per your Java and DB versions.

lib/c3p0-0.9.5.5.jar
lib/mchange-commons-java-0.2.19.jar

If you are using Maven then you can add the following dependency.

<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.5</version>
</dependency>

Sunday, December 20, 2020

Spring WebFlux Example Using Functional Programming - Spring Web Reactive

In this post we’ll see a Spring web reactive example using Spring WebFlux functional programming model. The application built here is a RESTful web service with Spring Webflux and also includes a WebClient consumer of that service. Application uses Spring Boot and run on the default Netty server.

Saturday, December 19, 2020

Spring Web Reactive Framework - Spring WebFlux Tutorial

This Spring WebFlux tutorial gives an overview of the new reactive web framework- Spring WebFlux added in Spring version 5.0. It is fully non-blocking, helps you to write event driven, asynchronous logic and supports Reactive Streams back pressure.


Friday, December 18, 2020

Spring WebFlux Example Using Annotation-Based Programming - Spring Web Reactive

The post Spring Web Reactive Framework - Spring WebFlux Tutorial gives an overview of Spring web reactive. Building on that knowledge in this post we’ll see a Spring web reactive example using Spring WebFlux annotation-based programming model where @Controller and @RestController components use annotations to express request mappings, request input, exception handling, and more. The application built here is a RESTful web service with Spring Webflux and also includes a WebClient consumer of that service. Application uses Spring Boot and runs on the default Netty server.

Class And Object in Python

Python being an object oriented programming language works on the concept of creating classes and using objects of the class to access the properties and methods defined by the class.

What is a class

In object oriented programming class defines a new type. Class encapsulates data (variables) and functionality (methods) together. Once a class is defined it can be instantiated to create objects of that class. Each class instance (object) gets its own copy of attributes for maintaining its state and methods for modifying its state.

You can create multiple class instances, they all will be of the same type (as defined by the class) but they will have their own state i.e. different values for attributes.

Thursday, December 17, 2020

Constructor in Python - __init__() function

Constructor is a special method provided to initialize objects (assign values to its data members) when they are created. In Python __init__() special method is the constructor and this method is always called when an object is created.

Syntax of init() in Python

First argument in __init__() method is always self. Constructor may or may not have other input parameters i.e. other input parameters are optional.

def __init__(self, input_parameters):
 #initialization code
 ....
 ....

Wednesday, December 16, 2020

Connection Pooling Using C3P0 Spring Example

This post shows how to provide JDBC connection pooling using C3P0 data source in Spring framework. DB used in this example is MySQL.

Maven dependency for C3P0

<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.2</version>
</dependency>
Alternatively you can download the following jars and put them in the application’s classpath.
c3p0-0.9.5.2.jar
mchange-commons-java-0.2.11.jar

Tuesday, December 15, 2020

Spring JdbcTemplate With ResultSetExtractor Example

In the post Select Query Using JDBCTemplate in Spring Framework we have already seen an example of extracting data from ResultSet using RowMapper. A RowMapper is usually a simpler choice for ResultSet processing, mapping one result object per row but there is another option in Spring framework known as ResultSetExtractor which gives one result object for the entire ResultSet. In this post we’ll see an example of Spring JdbcTemplate with ResultSetExtractor.

Since ResultSetExtractor is a callback interface used by JdbcTemplate's query methods so you can use an instance of ResultSetExtractor with JdbcTemplate’s query method.

Monday, December 14, 2020

Spring JdbcTemplate Insert, Update And Delete Example

In the post Data access in Spring framework we have already seen how Spring provides templates for various persistence methods and how templates divide the data access code into fixed part and variable part. Where Spring framework manages the fixed part and custom code which is provided by the user is handled through callbacks. In this post we’ll see how to use Spring JdbcTemplate to insert, update and delete data from the database.

Note that JdbcTemplate needs a DataSource in order to perform its management of fixed part like getting a DB connection, cleaning up resources.
In this post Apache DBCP is used for providing pooled datasource and MYSQL is used as the back end.

Async Pipe in Angular With Examples

Of all the built-in pipes in Angular, Async pipe is a little different as it subscribes to an Observable or Promise and returns the latest value it has emitted. When the component gets destroyed, the async pipe unsubscribes automatically to avoid any memory leaks.


Friday, December 11, 2020

Connection Pooling With Apache DBCP Spring Example

This post shows how to provide JDBC connection pooling using Apache DBCP data source in Spring framework. DB used in this example is MySQL.

Maven dependency for DBCP

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
    <version>2.1</version>
</dependency>

Alternatively you can download the following jars and put them in the classpath.

commons-dbcp2-2.1.1.jar
commons-pool2-2.5.0.jar
commons-logging-1.2.jar

Thursday, December 10, 2020

Pure and Impure Pipes in Angular

When you create a custom pipe in Angular there is one more attribute of @Pipe decorator which you can assign a value as true or false, that attribute is pure. In this tutorial we’ll see what are pure and impure pipes in Angular and what are the differences between pure and impure pipes.

@Pipe({
  name: 'myCustomPipe', 
  pure: false/true
})
export class MyCustomPipe {

}

By default, pipes are defined as pure so you don't explicitly need to assign value of pure as true.

Wednesday, December 9, 2020

Custom Pipe in Angular With Example

Though there are many Angular built-in pipes for data transformation but Angular framework also gives you an option to create a custom pipe to cater to custom data transformation. In this tutorial we’ll see how to create a custom pipe in Angular.

Creating custom pipe in Angular

To mark a class as a pipe apply the @Pipe decorator to the class. In the name attribute of the of @Pipe provide the name of the pipe. Use name in template expressions as you would for a built-in pipe.

Your custom pipe class should also implement the PipeTransform interface.

Sunday, December 6, 2020

CopyOnWriteArraySet in Java With Examples

In Java 5 many concurrent collection classes are added as a thread safe alternative for their normal collection counterparts which are not thread safe. Like ConcurrentHashMap as a thread safe alternative for HashMap, CopyOnWriteArrayList as a thread safe alternative for ArrayList. Same way CopyOnWriteArraySet in Java is added as a thread safe alternative for HashSet in Java.

CopyOnWriteArraySet class in Java

CopyOnWriteArraySet implements the Set interface (Actually it extends the AbstractSet class which in turn implements the set interface). Since CopyOnWriteArraySet implements the Set interface so basic functionality of the Set that only unique elements can be added applies to CopyOnWriteArraySet too.

Tuesday, December 1, 2020

Using Angular Pipes in Component or Service Classes

In this tutorial we’ll see how to use Angular pipe in Component classes and Service classes in Angular.

Steps to use angular pipes in component classes (or Service)

If you want to use the pipe in more than one component class then configure it in app.module.ts class-

  1. Import the required Angular pipe and add it to the providers array.
  2. In the Component class inject the pipe and use it.

You can do these steps in Component class itself if specific Angular pipe is used in that class only.

Using Angular pipes in component class example

We’ll create a simple reactive form with fields to enter date and amount. Date has to be transformed using the DatePipe and amount using the CurrencyPipe in Component. For DatePipe configuration is done in App module where as for CurrencyPipe it is done in the Component class itself.