Java exception encountered during initialization

How to Fix Exception in thread «main» java.lang.ExceptionInInitializerError in Java Program? Example

JVM throws java.lang.ExceptionInInitializerError , when there is an Exception inside static initializer block. If you know about static variables in Java, then you may know that they are initialized at the time of class loading. If there is an Exception during that initialization of static variables, you will see ExceptionInInitializerError in Java. This could be any exception e.g. java.lang.ArrayIndexOutOfBound or java.lang.NullPointerException . Java developers are often confused with this error because they think that they have not defined any static initializer block, then how come they are getting ExceptionInInitializerError; well, by default Java combines all static variable initialization inside a static initializer block and initialize them in the order they are declared in the source file.

I suppose a variable ABC is declared at line 1, used at line 2 but initialized at line 3, then code at line 2 will throw java.lang.NullPointerException , which will be wrapped by JVM in ExceptionInInitializerError , and if that code happens to be executed by the main thread then you will see «Exception in thread «main» java.lang.ExceptionInInitializerError» in your console or log file.

In a large application with huge log files sometimes this error got unnoticed, and programmers get alerted by the dreaded java.lang.NoClassDefFoundError. Unfortunately, this error comes when the client class tries to use the class, which was not loaded because of ExceptionInInitializerError . Since class loading was failed earlier, JVM is now throwing NoClassDefFoundError .

Sometimes this misleads Java developers, and they start looking at classpath, path and java.library.path for missing class and confused them with hell not finding any anomalies. If you are investigating the cause of NoClassDefFoundError, it’s always a better idea to check your application log files for ExceptionInInitializerError before looking at CLASSPATH .

In this article, we will see an example code, which generates exceptions during static initialization and results in «Exception in thread «main» java.lang.ExceptionInInitializerError» . In the later part, we will see how to fix this error.

Читайте также:  Sql server error incorrect syntax near

Cause of «Exception in thread «main» java.lang.ExceptionInInitializerError»

Now if you look at full stack trace carefully, you don’t need to do anything because JVM prints name of the class, which caused ExceptionInInitializerError . It’s also a subclass of LinkageError , which means if this error has occurred then your class will not be loaded into JVM memory. Now let’s take a look at our example program, which upon execution, throwing the following error :

By looking at this stack trace, we know that the actual error is java.lang.IndexOutOfBoundsException , which came at line 12 of StaticInitiazerDemo class. It came because of call to get() method of ArrayList with index 0 and come because the size of ArrayList was also zero (Index: 0, Size: 0 part of stack-trace). Now by following this information, you know that our List is empty when we try to get the first CreditCard from this list.

Here is a class hierarchy of all Error class in Java. You can see that ExceptionInInitializerError inherit from LinkageError. Its also worth knowing that like RuntimeException, Errors are also unchecked and compiler doesn’t check for mandatory error handling code.

Things to remember:

1) Remember «Exception in thread «main» java.lang.ExceptionInInitializerError» means Exception has occurred in the main thread, and it is java.lang.ExceptionInInitializerError , which is a subclass of LinkageError and comes when JVM tries to load a class and it failed because of any RuntimeException in static initializer block e.g. IndexOutOfBoundsException or NullPointerException.

2) Remember that JVM combines all static variable initialization into one static initializer block in the order they appear in the source file. So, don’t think that absence of an explicit static initializer block will not cause this error. In fact, you must ensure the correct order of static variables i.e. if one variable initialization uses another variable then make sure that is initialized first.

3) Down the line, java.lang.ExceptionInInitializerError can cause ClassNotFoundException or NoClassDefFoundError, if some other code tries to use the class, which caused ExceptionInInitializerError . Why? because loading of that class is failed and it’s not available inside JVM memory. So always check your log files for this before even if you are looking to solve any problem related to class not found.

Читайте также:  Error log class php

4) Remember Static initializer block can throw RuntimeException but not checked Exception because later required mandatory catch block for handling.

Источник

How to solve this : Exception encountered during context initialization — cancelling refresh attempt?

I am new to spring and hibernate and trying to create simple webapp. but i am stuck on this error for several days.When I tried to run junit test this error is showing. what am i missing here?

my entity class Category.java

PageController.java

CategoryDAOimpl.java

interfaceCategoryDAO.java

HibernateConfig.java

CategoryTestCase.java

pom.xml

I go through other similar questions but that dosen’t help.

SOLUTION 1 :

As confirmed by the user,

Adding @Bean to SessionFactory has resolved the issue,

SOLUTION 2 :

Exception encountered during context initialization — cancelling refresh attempt

In this article, we are discussing the Spring org.springframework.beans.factory. NoUniqueBeanDefinitionException — this is a common exception thrown by the BeanFactory when it is unable to set the property of any bean.

DescriptionException thrown on an attempt to set the value of a property that is not writable (typically because there is no setter method)

Complete Exception Stack Trace

Let’s see when this Exception occurs with an Example:

Spring Configuration File:

CoreDao Class:

Client Code:

Cause Of Exception:All code is okay but if we look into the applicationContext.xml file , we can easily see that we are setting the value of name attribute of CoreDao class with property tag but we did not have any setter method of ‘name’ attribute of CoreDao class that is the cause of the exception.

Solution:Just generate setter and getter method for ‘name’ attribute of CoreDao class as mentioned below, and all code will work fine

Источник

Почему не создается бин jpaRepository?

Первый раз деплою. через идею все нормально отрабатывает, но при попытке задеплоить на vps выдает ошибку, гитхаб проект
Стекрейс ошибки:

Сам пытался понять в чем проблема весь день, ни 1 из способов, найденных в интернете не помог..

  • Вопрос задан более двух лет назад
  • 2751 просмотр

No bean named ‘entityManagerFactory’ available

Первый раз деплою. через идею все нормально отрабатывает, но при попытке задеплоить на vps выдает ошибку

Если у вас локально отрабатывает корректно, а на VPS нет, то проверьте конфигурацию сервера. В вашем проекте на гитхаб application.yaml пустой и соответственно, непонятно что именно у вас прописано в конфигах для production. Если у вас есть профили, то проверьте установлен ли hibernate.ddl-auto: validate и если установлен, то импортировали ли вы ddl & dml на сервер. Или у вас он на production должен создать ddl сам?
Как минимум, это первый момент на что стоит обратить внимание.

Читайте также:  Skyworth 50g2a прошивка emmc

Далее стоит уточнить деплоите ли вы приложение на внешний томкат или используете embedded?
Далее попробуйте добавить такой класс в ваш проект:

Далее обратите внимание на то, как именно вы собираете build и что в него добавляете. Например, war exploded или war или jar. Есть ли все необходимые классы в нем и т.д.

Если сборка происходит через Gradle, то используйте bootWar. В общем, нужно проводить дебаг и смотреть что не так

Источник

Spring Startup Exceptions: UnsatisfiedDependencyException and NoSuchBeanDefinitionException

Overview

When developing Java applications using the Spring Framework, our code may compile successfully but application startup will fail if something isn’t configured correctly in Spring.

In this article, we’ll explain why these happen and how to fix them. Since Spring beans can be configured using either Java annotations or XML, we’ll cover both approaches.

Exceptions

Spring attempts to create beans and wire them up during application startup.

UnsatisfiedDependencyException

Spring is telling us that it could not inject a dependency for one of our classes.

This exception is often triggered by another exception called NoSuchBeanDefinitionException.

NoSuchBeanDefinitionException

Spring is telling us that it couldn’t find a corresponding bean in the application context. The application context is the container where Spring-managed beans live.

This can happen for a couple reasons:

  • There are no beans defined by that name or type
  • There is more than one bean defined but Spring was unable to determine which one to use

Code Examples

In order to demonstrate these exceptions, we’ll start with working code examples and then break them on purpose.

Spring Boot (annotation-based configuration)

DemoApplication.java

This is a standard main method for a Spring Boot application.

The @SpringBootApplication annotation on line 6 enables component scanning which means that classes will be scanned for specific annotations for the purposes of automatic bean creation.

UserService.java

Let’s create an empty service named UserService :

Источник

Smartadm.ru
Adblock
detector