Reputation: 563
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
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
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
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