Rytek
Rytek

Reputation: 563

Spring - Instanciate a bean with a class which throws an Exception

I'm trying to instanciate a bean which constructor could throw an Exception. I can't modify this class (given by an external team).

<bean id="myClass" class="myClass" />

The myClass constructor throws Exception.

I've been thinking about extending this class with a Singleton Pattern which is the behavior I want (be sure to instantiate only one instance of MyClass).

Error message :

nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myClass' defined in class path resource [.../spring_applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [myClass]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError

Thanks in advance for your answers

I think the problem comes from the fact that my constructor throws an Exception.

My question is : with Spring, is it possible to instanciate a bean with a constructor which could throw an exception ?

Upvotes: 3

Views: 5520

Answers (3)

Magesh Pachiyappan
Magesh Pachiyappan

Reputation: 146

As per stack trace, looks like there is an unexpected error either in static block or variable while creating an object of class 'myClass'.

Upvotes: 0

Ajinkya
Ajinkya

Reputation: 22720

If no bean scope is specified in bean configuration file, default to singleton. Your bean myClass is a singleton and you dont need to do anything more.
Spring Doc

Upvotes: 3

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16060

Spring beans are by default singletons.

You should provide more of the stacktrace - what you're showing indicates that it is not myClass that is the problem, but the ClassPathXmlApplicationContext constructor that throws an exception - the cause usually follows later in the stacktrace.

Cheers,

Upvotes: 1

Related Questions