0

Basically, the code I have is here below. Take into account that this is a "test" state of the code. The original problematic was a call on init() to a different class that threw a checked exception. This throw was catched by a try/catch block, then the application failed when trying to create the exception. All that has been removed for clarity's sake, as the problem was in the "MyCustomRuntimeException" creation.

@Component
public class ClassName {

  public ClassName() {
    //minor, non problematic operations.
  }

  @PostConstruct
  public void init() {
    throw new MyCustomRuntimeException("AAAAAAAH");
  }

}

MyCustomRuntimeException is defined like this:

public class MyCustomRuntimeException extends RuntimeException {

  public MyCustomRuntimeException (String message) {
    super(message);
  }
}

And, I'm getting an "UnsatisfiedDependencyException" when creating a class that uses this class. The console points towards the line where the new MyCustomRuntimeException is being thrown, and I don't really get what's going on.

Also, "MyCustomRuntimeException" started as a regular exception, but I saw that I should throw a RunTimeException instead because the @PostConstruct forbids checked exceptions to be thrown. And I've also tried to throw a standard RunTimeException with no luck.

So, I'm clueless here. Any ideas on why I can't throw this exception?

Neuromante
  • 531
  • 2
  • 12
  • 29
  • I've tested and i can throw RuntimeException (or custom exception) in a spring boot project in @postconstruct method. I think you have to focus on "UnsatisfiedDependencyException" and its "caused by" section. – classeswilldullyourmind Mar 19 '20 at 12:23
  • What do you expect would happen? Your bean cannot be constructed, due to the exception, then another bean that depends on this cannot get the dependency on this bean because it never got created? So I don't see the problem and it actually works as it should. – M. Deinum Mar 19 '20 at 12:26
  • @M.Deinum Ah, you're right. I misunderstood how Spring was handling the bean creation and somehow thought it would not fail when launching. I can totally accept that as a reply if you want to write it as a proper answer, thanks! – Neuromante Mar 19 '20 at 14:23

1 Answers1

3

Every bean in the context needs to be correctly created. When an error occurs the creation of beans will stop/fail and the context (or in other words your Application) will not start.

You get an UnsatisfiedDependencyException due to the fact that the ClassName bean is created because it is needed by the other bean. After construction of ClassName it will call the @PostConstruct of the ClassName bean, and that fails due to an exception. Hence the instance doesn't get created, hence an UnsatisfiedDependencyException.

The root cause of the UnsatisfiedDependencyException will be the exception thrown by your own initializer method.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224