Category Archives: Spring

Spring Scheduling Annotations List


After Spring Boot, Spring enhanced with scheduling and Asynchronous annotations which added with methods along with some information about to execute it, and Spring takes care of rest.

These annotations are from the org.springframework.scheduling.annotation package. Below are most common annotations which we use at time of development:

See Also :

Spring Scheduling Annotations

@EnableAsync

@EnableAsync annotation enable asynchronous functionality in Spring. It must use with @Configuration.

@Configuration
@EnableAsync
class VehicleFactoryConfig {}

Now, that we enabled asynchronous calls, we can use @Async to define the methods supporting it.

@EnableScheduling

@EnableScheduling annotation enable scheduling in the application. We should always use it in conjunction with @Configuration:

@Configuration
@EnableScheduling
class VehicleFactoryConfig {}

Now we are enabled with Schedule, we can now run methods periodically with @Scheduled.

@Async

@Async apply on methods which we want to execute on a different thread, hence run them asynchronously.

@Async
void repairCar() {
    // ...
}

If we apply @Aynch annotation to a class, then all methods will be called asynchronously.

Note: Before applying @Async on method first we need to enabled the asynchronous calls for this annotation to work, with @EnableAsync or XML configuration.

@Scheduled

@Scheduled annotation use to execute a method periodically at fixed interval or by Cron like expressions.

For Example : The first execution of the task will be delayed by 5 seconds and then it will be executed normally at a fixed interval of 2 seconds.

@Scheduled(fixedRate = 2000 , initialDelay=5000)
void checkVehicle() {
    // ...
}

After Java 8 with repeating annotations feature, @Scheduled can mark multiple times on a method with different period or Cron expressions.

For Example : The first execution of the task will be delayed by 5 seconds and then it will be executed normally at a fixed interval of 2 seconds and cron expression will execute on Monday to Saturday on 12 PM.

@Scheduled(fixedRate = 2000)
@Scheduled(cron = "0 * * * * MON-SAT")
void checkVehicle() {
    // ...
}

Note:

  • Before applying @Scheduled on method first we need to enabled the scheduling calls by applying @EnableScheduling configuration. that the method annotated with @Scheduled should have a void return type.
  • The method having @Scheduled should have a void return type.

@Schedules

@Schedules annotation use to specify multiple @Scheduled rules.

@Schedules({
  @Scheduled(fixedRate = 2000),
  @Scheduled(cron = "0 * * * * MON-SAT")
})
void checkVehicle() {
    // ...
}

Note: Same feature can achieve  since Java 8 with repeating annotations as described above.

Spring Bean Annotations List


Here you will know about most common Spring Bean Annotations to create different type of beans. We can create spring beans by declaring 3 ways:

  1. Declare bean using XML configuration
  2. Declare bean with @Bean annotations in @Configuration class.
  3. Declare bean with one on type from org.springframework.stereotype package and leave the rest to component scanning.

Here we will mainly focus on annotations which help for creating beans:

See Also :

Component Scanning

Spring can automatically scan a package or class if  component scanning is enabled.

We can configure component scanning parameter as below:

  • Use basePackages to scan @Configuration classes from package.
  • Use basePackageClasses to scan .
  • If no argument is specified, the scanning happens from the same package where the @ComponentScan annotated class is present.

Component Scan from Packages

@Configuration
@ComponentScan(basePackages = "com.fiot.annotations")
class VehicleFactoryConfig {}

Component Scan from Classes

@Configuration
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}

Both arguments are arrays so that we can provide multiple packages for each. After Java 8 we can use repeating annotation also.

@Configuration
@ComponentScan(basePackages = "com.fiot.annotations")
@ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
class VehicleFactoryConfig {}

or

@Configuration
@ComponentScans({
  @ComponentScan(basePackages = "com.fiot.annotations"),
  @ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
})
class VehicleFactoryConfig {}

Component Scan XML Configuration


@Component

@Component is a class level annotation. During the component scan, Spring Framework automatically detects classes annotated with @Component.

@Component
class CarUtility {
    // ...
}

Note: By default, the bean instances @Component class have the same name as the class name with a lowercase initial. On top of that, we can specify a different name using the optional value argument of this annotation.

Since @Repository, @Service, @Configuration, and @Controller are all meta-annotations of @Component, they share the same bean naming behavior. Also, Spring automatically picks them up during the component scanning process.

@Repository

@Repository annotation use to represent DAO or Repository classes of database access layer in an application.

@Repository
class VehicleRepository {
    // ...
}

Main  advantage of using @Repository annotation is that it has automatic persistence exception translation enabled. When using a persistence framework such as Hibernate, native exceptions thrown within classes annotated with @Repository will be automatically translated into subclasses of Spring’s DataAccessExeption.
To enable exception translation, we need to declare our own PersistenceExceptionTranslationPostProcessor bean:

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

@Service

@Service annotation use for service layer classes as business logic of an application usually resides within the service layer.

@Service
public class VehicleService {
    // ...
}

@Controller

@Controller is a class level annotation which tells the Spring Framework that this class serves as a controller in Spring MVC.

@Controller
public class VehicleController {
    // ...
}

@Configuration

Configuration classes can contain bean definition methods annotated with @Bean:

@Configuration
class VehicleFactoryConfig {

    @Bean
    Engine engine() {
        return new Engine();
    }
}

Stereotype Annotations with AOP

Spring stereotype annotations, makes easy to create a pointcut that targets all classes that have a particular stereotype.

For example: Suppose we want to measure the execution time and performance of methods from the DAO layer. We’ll create the following aspect (using AspectJ annotations) taking advantage of @Repository stereotype:

@Aspect
@Component
public class PerformanceAspect {
    @Pointcut("within(@org.springframework.stereotype.Repository *)")
    public void daoClassMethods() {};

    @Around("daoClassMethods()")
    public Object measureMethodExecutionTime(ProceedingJoinPoint joinPoint)
      throws Throwable {
        long start = System.nanoTime();
        Object returnValue = joinPoint.proceed();
        long end = System.nanoTime();
        String methodName = joinPoint.getSignature().getName();
        System.out.println(
          "Execution of " + methodName + " took " +
          TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
        return returnValue;
    }
}

In this example, we have created a pointcut that matches all methods in classes annotated with @Repository. We used the @Around advice to then target that pointcut and determine the execution time of the intercepted methods calls. Same approach can be apply on other layer of application.

Spring Core Annotations List


Here you will know about all Spring core related annotations which leverage the capabilities of Spring DI engine using annotations in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages. I have categorized Sping core annotations in two categories:

  1. DI (Dependency Injection) Related Annotations
  2. Context Configuration Annotations

See Also :

DI Related Annotations

@Bean

@Bean marks as factory method which instantiates a Spring bean. Spring calls these methods when a new instance of the return type is required. Bean will have same name as factory method.

@Bean
Engine engine() {
    return new Engine();
}

If you want to name it differently, we can do so with the name of the value arguments of this annotation.

@Bean("engine")
Engine getEngine() {
    return new Engine();
}

Note: All these @Bean annotated methods must be in @Configuration classes.

@Autowired

@Autowired to mark a dependency which Spring is going to resolve and inject. We can use this annotation with a constructor, setter, or field injection.

Constructor injection:

class Car {
    Engine engine;

    @Autowired
    Car(Engine engine) {
        this.engine = engine;
    }
}

Setter injection:

class Car {
    Engine engine;

    @Autowired
    void setEngine(Engine engine) {
        this.engine = engine;
    }
}

Field injection:

class Car {
    @Autowired
    Engine engine;
}

Note :

  • @Autowired has a boolean argument called required with a default value of true. If fields are autowired and Spring’s not found any suitable bean to wire then it will throw an exception to handle such case make Autowire as required false.
  • After version 4.3, we don’t need to annotate constructors with @Autowired explicitly unless we declare at least two constructors.

@Qualifier

@Qualifier use along with @Autowired to provide the bean id or bean name we want to use in ambiguous situations. For example : Following two beans implement the same interface

class Bike implements Vehicle {}
class Car implements Vehicle {}

If Spring needs to inject a Vehicle bean, it ends up with multiple matching definitions. To resolve such ambiguity , we can provide a bean’s name explicitly using the @Qualifier annotation.
Using constructor injection:

@Autowired
Biker(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

Using setter injection:

@Autowired
void setVehicle(@Qualifier("bike") Vehicle vehicle) {
    this.vehicle = vehicle;
}

or

@Autowired
@Qualifier("bike")
void setVehicle(Vehicle vehicle) {
    this.vehicle = vehicle;
}

Using field injection:

@Autowired
@Qualifier("bike")
Vehicle vehicle;

@Required

@Required on setter methods to mark dependencies that we want to populate through XML.

@Required
void setColor(String color) {
    this.color = color;
}

<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Otherwise, BeanInitializationException will be thrown.

@Value

@Value use as a placeholder for injecting property values into beans. It’s compatible with a constructor, setter, and field injection.
Constructor injection:

Engine(@Value("10") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

Setter injection:

@Autowired
void setCylinderCount(@Value("10") int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

or

@Value("10")
void setCylinderCount(int cylinderCount) {
    this.cylinderCount = cylinderCount;
}

Field injection :

@Value("10")
int cylinderCount;

Placeholder from properties file : We can use placeholder strings in @Value to wire values defined in external sources, for example, in .properties or .yaml files.
Let’s assume the following .properties file having below value:

engine.fuelType=diesel

We can inject the value of engine.fuelType with the following:

@Value("${engine.fuelType}")
String fuelType;

We can use @Value even with SpEL.

@DependsOn

@DependsOn annotation uses to initialize other beans before the annotated one. Usually, this behavior is automatic, based on the explicit dependencies between beans. @DependsOn use when the dependencies are implicit. For example: JDBC driver loading or static variable initialization.

@DependsOn  annotations need an array containing the dependency bean names.

@DependsOn("engine")
class Car implements Vehicle {}

Alternatively, if we define a bean with the @Bean annotation, the factory method should be annotated with @DependsOn:

@Bean
@DependsOn("fuel")
Engine engine() {
    return new Engine();
}

@Lazy

@Lazy  annotations use when we need to initialize our bean lazily when we request it. By default, all singleton beans create eagerly at the startup/bootstrapping of the application context.

@Lazy annotation behaves differently depending on where we exactly place it :

  • A @Bean annotated bean factory method, to delay the method call (hence the bean creation).
  • A @Configuration class and all contained @Bean methods will be affected
  • A @Component class, which is not a @Configuration class, this bean will be initialized lazily.
  • An @Autowired constructor, setter, or field, to load the dependency itself lazily (via proxy).

By Default @Lazy annotation value is true. It is useful to override  the default behavior.
For example :

  • Marking beans to be eagerly loaded when the global setting is lazy.
  • Configure specific @Bean methods to eager loading in a @Configuration class marked with @Lazy.
@Configuration
@Lazy
class VehicleFactoryConfig {

    @Bean
    @Lazy(false)
    Engine engine() {
        return new Engine();
    }
}

@Lookup

@Lookup annotated method tells Spring to return an instance of the method’s return type when we invoke it.

@Primary

@Primary annotation use to make specified bean as default when define multiple beans of the same type. Otherwise, beans which are not having @Qualifier then injection will be unsuccessful because Spring has no clue which bean we need.
We can use @Primary to simplify this case: if we mark the most frequently used bean with @Primary it will be chosen on unqualified injection points.

@Component
@Primary
class Car implements Vehicle {}

@Component
class Bike implements Vehicle {}

@Component
class Driver {
    @Autowired
    Vehicle vehicle;
}

@Component
class Biker {
    @Autowired
    @Qualifier("bike")
    Vehicle vehicle;
}

In the previous example Car is the primary vehicle. Therefore, in the Driver class, Spring injects a Car bean. Of course, in the Biker bean, the value of the field vehicle will be a Bike object because it’s qualified.

@Scope

@Scope annotation use to define the scope of a @Component class or a @Bean definition. It can be either singleton, prototype, request, session, global session or some custom scope. By default scope of bean is a singleton.
For example:

@Component
@Scope("prototype")
class Engine {}

Context Configuration Annotations

We can configure the application context with the annotations described in this section.

@Profile

When we want to use a specific @Component class or a @Bean method only when a specific profile is active, we can mark it with @Profile. We can configure the name of the profile with the value argument of the annotation:

@Component
@Profile("sportDay")
class Bike implements Vehicle {}

@Import

We can use specific @Configuration classes without component scanning with this annotation. We can provide those classes with @Import‘s value argument:

@Import(VehiclePartSupplier.class)
class VehicleFactoryConfig {}

@ImportResource

We can import XML configurations with this annotation. We can specify the XML file locations with the locations argument, or with its alias, the value argument:

@Configuration
@ImportResource("classpath:/annotations.xml")
class VehicleFactoryConfig {}

@PropertySource

With this annotation, we can define property files for application settings:

@Configuration
@PropertySource("classpath:/annotations.properties")
class VehicleFactoryConfig {}

@PropertySource leverages the Java 8 repeating annotations feature, which means we can mark a class with it multiple times:

@Configuration
@PropertySource("classpath:/annotations.properties")
@PropertySource("classpath:/vehicle-factory.properties")
class VehicleFactoryConfig {}

@PropertySources

We can use this annotation to specify multiple @PropertySource configurations:

@Configuration
@PropertySources({
    @PropertySource("classpath:/annotations.properties"),
    @PropertySource("classpath:/vehicle-factory.properties")
})
class VehicleFactoryConfig {}

Note: After Java 8+ we can achieve the same with the repeating annotations feature as described above.

Spring Web and REST Annotations List


Here you will know about  all  Spring Web & REST services related annotations which we mostly used while development of applications:

See Also :

Spring Web & REST Annotations

@RequestMapping

@RequestMapping can be configured using path, or it’s aliases, name and value. @RequestMapping annotations apply at class and method level as request handler methods inside the @Controller classes.
@RequestMapping parameters:

  • URL : the method is mapped to
  • method : compatible HTTP methods/li>
  • params : filters requests based on presence, absence or value of HTTP headers
  • headers : filters requests based on presence, absence or value of HTTP params
  • consumes: which media types the method can consume in the HTTP request body
  • produces: which media types the method can produce in the HTTP response body

@RequestMapping variants for HTTP methods:

  • @GetMapping :For GET method
  • @PostMapping : For POST method
  • @PutMapping : For PUT method
  • @DeleteMapping :For Delete Method
  • @PatchMapping : For Patch Method

Example : Method level

@Controller
class CarController {

    @RequestMapping(value = "/cars/welcome", method = RequestMethod.GET)
    String welcome() {
        return "Facing Issues On IT";
    }
}

Example :Class level (both are equivalent)
@RequestMapping at class level that provide default settings for all handler methods in as @Controller class and for method handler URL that will be combination of path at class level and method level.

@Controller
@RequestMapping(value = "/cars", method = RequestMethod.GET)
class CarController {

    @RequestMapping("/welcome")
    String welcome() {
        return "Facing Issues on IT";
    }
}

@RequestBody

@RequestBody map the body of Http request to an object. Deserialization is automatic and depend on content type of request.
Example

@RequestMapping(value="/car/create", method=RequestMethod.POST)
public ResponseEntity createCar(@RequestBody Car , UriComponentsBuilder ucBuilder){
    System.out.println("Creating Car "+car.getName());

    if(userService.isUserExist(user)){
        System.out.println("A Car with name "+car.getName()+" already exist");
        return new ResponseEntity(HttpStatus.CONFLICT);
    }

    carService.saveCar(car);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(car.getId()).toUri());
    return new ResponseEntity(headers, HttpStatus.CREATED);
}

@PathVariable

@PathVariable indicates that a method argument is bound to a URI template variable. We can specify the URI template with the @RequestMapping annotation and bind a method argument to one of the template parts with @PathVariable. We can achieve this with the name or its alias, the value argument.
Example : Path variable with different name

@RequestMapping("/{id}")
Car getCar(@PathVariable("id") long carId) {
    // ...
}

Example : Path variable with same name
If the name of the part in the template matches the name of method argument then no need to specify the @PathVariable annotation.

@RequestMapping("/{carId}")
Car getCar(@PathVariable long carId) {
    // ...
}

Example : Path variable as optional
We can make @PathVariable as optional by setting the argument required to false.

@RequestMapping("/{id}")
Car getCar(required = false) long id) {
    // ...
}

@RequestParam

@RequestParam use to access HTTP request parameters. It has the same configuration options as the @PathVariable annotation. We can access them with the annotations @CookieValue and @RequestHeader respectively.

Example

@RequestMapping
Car getCarDetailByParam(@RequestParam("id") long id) {
    // ...
}

Example : Set defaultValue to make required false
In @RequestParam can inject default value by setting defaultValue (i.e required false) that will consider when spring founds no and empty value in request.

@RequestMapping("/price")
Car buyCar(@RequestParam(defaultValue = "6") int seatCount) {
    // ...
}

@ResponseBody

Mark a request handler method with @ResponseBody then Spring treats the result of the method as the response itself.

If annotate a @Controller class with @ResponseBody annotation then all request handler methods will use it.

Example

@ResponseBody
@RequestMapping("/hello")
String hello() {
    return "Facing Issues on IT";
}

@ExceptionHandler

@ExceptionHandler can use to declare a custom error handler method. Spring calls this method when a request handler method throws any of the specified exceptions.The caught exception can be passed to the method as an argument:
Example


@ExceptionHandler(IllegalAccessException.class)
void onIllegalAccessException(IllegalAccessException exception) {
    // ...
}

@ResponseStatus

@ResponseStatus annotation use to specify the desired HTTP status of the response if we annotate a request handler method with this annotation. We can declare the status code with the code argument, or its alias, the value argument. Also, we can provide a reason using the reason argument and also use it along with @ExceptionHandler:
Example

@ExceptionHandler(IllegalAccessException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
void onIllegalAccessException(IllegalAcessException exception) {
    // ...
}

@Controller

We can define a Spring MVC controller with @Controller.
Example
As used in below example

@RestController

The @RestController combines @Controller and @ResponseBody.
Example
Both are alternate way to handle rest services

@Controller
@ResponseBody
class VehicleRestController {
    // ...
}

or

@RestController
class VehicleRestController {
    // ...
}

@ModelAttribute

@ModelAttribute annotation can access elements that are already in the model of an MVC @Controller, by providing the model key.

  • Like @PathVariable and @RequestParam no need to specify the model key if the argument has the same name.
  • If we annotate a method with @ModelAttribute Spring will automatically add the method’s return value to model.

Example

@PostMapping("/assemble")
void assembleCar(@ModelAttribute("car") Car carModel) {
    // ...
}

or here model attribute name is same.

@PostMapping("/assemble")
void assembleCar(@ModelAttribute Car car) {
    // ...
}

Before Spring calls a request handler method, it invokes all @ModelAttribute annotated methods in the class. We can use below either way to get value of vehicle model attribute.

@ModelAttribute("car")
Car getCar() {
    // ...
}

or

@ModelAttribute
Car car() {
    // ...
}

@CrossOrigin

@CrossOrign annotation enables cross-domain communication for the annotated request handler methods. If we mark a class with @CrossOrgin then it applies to all request handler methods in it.
Example

@CrossOrigin
@RequestMapping("/welcome")
String welcome() {
    return "Facing Issues On IT";
}

Spring Boot Annotations List


Here you will know about  all Spring Boot related annotations which we mostly used while development of applications:

See Also :

Spring Boot Annotations

Annotations & Description
@SpringBootAnnotation : This annotation is use to mark the main class of Spring boot application. It encapsulate below transactions with it’s default value.

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

Example

@SpringBootApplication
class CarFactoryApplication {

    public static void main(String[] args) {
        SpringApplication.run(CarFactoryApplication.class, args);
    }
}
@EnableAutoConfiguration : Spring boot looks for auto-configuration beans on its classpath and automatically applies them.
Note: Always use this annotaion with @Configuration.Usually, when we write auto-configuration, use them conditionally with @Configuration classes or @Bean methods. as given in below annotations:
Example

@Configuration
@EnableAutoConfiguration
class CarFactoryConfig {}
@ConditionalOnClass and @ConditionalOnMissingClass
These annotations use when need to marked auto-configuration bean if the class in the annotation’s argument is present/absent.
Example

@Configuration
@ConditionalOnClass(DataSource.class)
class DBConfiguration {
    //…
}
@ConditionalOnBean and @ConditionalOnMissingBean
These annotations use when need to define conditions based on the presence or absence of a specific bean.
Example

@Bean
@ConditionalOnBean(name = "dataSource")
LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    // …
}
@ConditionalOnProperty :
This annotation is use when need to apply condition based on properties values.
Example

@Bean
@ConditionalOnProperty(
    name = "useoracle",
    havingValue = "local"
)
DataSource dataSource() {
    // ...
}
@ConditionalOnResource :
This annotation will use a definition only when a specific resource is present.
Example

@ConditionalOnResource(resources = "classpath:database.properties")
Properties additionalProperties() {
    // ...
}
@ConditionalOnWebApplication and @ConditionalOnNotWebApplication :
Use these annotations, when condition need to check if the current application is or isn’t a web application.
Example

@ConditionalOnWebApplication
HealthCheckController healthCheckController() {
    // ...
}
@ConditionalExpression :
This annotation use in more complex situations and marked definition when the SpEL expression is evaluated to true.
Example

@Bean
@ConditionalOnExpression("${useoracle} && ${oracleserver == 'local'}")
DataSource dataSource() {
    // ...
}
@Conditional :
For more complex conditions, we can create a class for evaluating the custom condition.
Example

@Conditional(HibernateCondition.class)
Properties additionalProperties() {
    //...
}

[Solved] java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver


JDBC or Springboot or hibernate throw this exception when you mentioned driver as org.hsqldb.jdbcDriver in your JDBC code or XML configuration or data source configuration properties file but required database driver jar or dependencies is not added in class path.

This exception occurs by below methods :

  • The forName method in the class Class.

                 Class.forName(java.lang.String)

  • The findSystemClass method in the class ClassLoader.

                ClassLoader.findSystemClass()

  • The loadClass method in class ClassLoader.

                ClassLoader.loadClass(java.lang.String, boolean)

java.lang.ClassNotFoundException is Checked Exception which is subclass of  java.lang.ReflectiveOperationException. This  is thrown when application load a class by String name whose definition is not found.

Constructors

  • ClassNotFoundException(): Constructs a ClassNotFoundException with no detail message.
  • ClassNotFoundException(String s) : Constructs a ClassNotFoundException with the specified detail message.
  • ClassNotFoundException(String s, Throwable ex) : Constructs a ClassNotFoundException with the specified detail message and optional exception that was raised while loading the class.

 Difference between Class.forName() and ClassLoader.loadClass()

Example 1: ClassNotFoundException

Below is example of connecting with database and retrieve data from sql table. This will throw ClassNotFoundException because sql driver jar is not in classpath. After this example also mentioned solution.

package example;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ClassNotFoundException1 {

public static void main(String[] args) {
try {
Class.forName("<strong>org.hsqldb.jdbcDriver</strong>");

Connection con = DriverManager.getConnection("jdbc:hsqldb:hsql//localhost:3306/FacingIssuesOnITDB", "root", "");

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select name from employee");
String dbtime;
while (rs.next()) {
dbtime = rs.getString(1);
System.out.println(dbtime);
}

con.close();

} catch (ClassNotFoundException | SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}

}

}

Output:

Connection Failed! Check output console
<pre><code>
<strong>java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver</strong>
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at org.springframework.util.ClassUtils.forName(ClassUtils.java:251)
	at org.springframework.jdbc.datasource.embedded.HsqlEmbeddedDatabaseConfigurer.getInstance(HsqlEmbeddedDatabaseConfigurer.java:48)
	at org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseConfigurerFactory.getConfigurer(EmbeddedDatabaseConfigurerFactory.java:43)
	... 54 common frames omitted
</code></pre>

Solutions:

For solving ClassNotFoundException by Class.ForName() method  considering above example to load MySQL driver same way you can follow for other classes and different DB drivers.

Solution in Eclipse :Follow below steps :

  • Right click your project folder and open up Properties.
  • From the right panel, select Java Build Path then go to Libraries tab.
  • Select Add External JARs to import the HSQLDB driver.
  • From the right panel, select Deployment Assembly.
  • Select Add…, then select Java Build Path Entries and click Next.
  • You should see the SQL driver on the list. Select it and click first.

Tomcat :

If directly running from tomcat. Just copy the HSQL-Connector.jar into Tomcat’s lib folder/directory, and then remove the jar from the webApp’s lib folder, and then, run the project.

Maven Springboot application

Add below dependency in your pom.xml file


<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
</dependency>

Summary :

  • Define what is ClassNotFoundException.
  • What are methods throws ClassNotFoundException?
  • Example for ClassNotFoundException.
  • How to fix ClassNotFoundException in Eclipse and Tomcat.
  • How to fix Springboot maven applications.

[Solved] JDBC, “Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException”


JDBC “java.io.NotSerializableException” occurs while using Spring JDBC Template for connectivity and passing arguments for searching/update as parameters. Because JDBC parameters always required searialize objects.

Mostly happen when forget to use get fields value from object and class is not serializable.

Example :

Exception Message

Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException

Class using

public class DynamicDashboard {
private int dashboardId;
private String dashboardName;
private String htmlContent;
private String scriptContent;
private String ruleContent;

public DynamicDashboard()
{
	super();
}

//Getter and Setters

Below is my DAO class method where this exception occured  for column RULE_CONTENT.

public void addDashboard(DynamicDashboard dynamicDashboard) {
		String sql = "INSERT INTO dynamic_dashboard "
				+ "(DASHBOARD_NAME, HTML_CONTENT,SCRIPT_CONTENT,RULE_CONTENT) VALUES (?, ?, ?,?)";

		try {
			jdbcTemplate = new JdbcTemplate(dataSource);

			jdbcTemplate.update(sql,
					new Object[] { dynamicDashboard.getDashboardName(), dynamicDashboard.getHtmlContent(),
							dynamicDashboard.getScriptContent(), dynamicDashboard});
		} catch (Exception ex) {
			logger.error(ex.getMessage());
		}

	}

In above method we forget to get last parameter value for rule like dynamicDashboard.getRuleContent()for database column RULE_CONTENT because JDBCTemplate always required serializable object and all wrapper classes(Integer, String etc.) are searializable. It will through exception “java.io.NotSerializableException” as above.

Solution :

Add get method for ruleContent for object dynamicDashboard.

Correct Code

public void addDashboard(DynamicDashboard dynamicDashboard) {
		String sql = "INSERT INTO dynamic_dashboard "
				+ "(DASHBOARD_NAME, HTML_CONTENT,SCRIPT_CONTENT,RULE_CONTENT) VALUES (?, ?, ?,?)";

		try {
			jdbcTemplate = new JdbcTemplate(dataSource);

			jdbcTemplate.update(sql,
					new Object[] { dynamicDashboard.getDashboardName(), dynamicDashboard.getHtmlContent(),
							dynamicDashboard.getScriptContent(), dynamicDashboard.getRuleContent()});
		} catch (Exception ex) {
			logger.error(ex.getMessage());
		}

	}

More Issues

For more JDBC issue solution follow link Common JDBC Issues.

Leave you feedback to enhance more on this topic so that make it more helpful for others.