I found similar question here Spring - how to inject a bean into class which is created many times at runtime? and Why is Spring's ApplicationContext.getBean considered bad? but neither really answers my case.
Example code:
public interface AppNameProvider
{
String getAppName();
}
public class DefaultAppNameProvider implements AppNameProvider
{
private String appName;
public String getAppName()
{
return appName;
}
public setAppName(String appName)
{
this.appName = appName;
}
}
<bean id="appNameProvider" class="some.package.DefaultAppNameProvider">
<property name="appName" value="MyApplication"/>
</bean>
public class MyException extends RuntimeException
{
// Imagine obligatory constructors here...
public String getAppName()
{
// Inject appNameProvider somehow here
return appNameProvider.getAppName();
}
}
I have a provider bean declared in xml. In the example the value is simply declared in xml for simplicity. I have a custom exception which needs to receive something from a bean. How to inject such bean into the exception class. I obviously can't declare exception as a Spring bean. The appName is just a simple example, it can be anything else. You might wonder why a hypothetic caller of myException.getAppName() wouldn't just simply call appNameProvider.getAppName()? Because it's not intended so, e.g. there might be different provider in each exception etc.
I would like to know how to inject the bean into such exception. I can add setter and set the provider at the exception throw time. But I have to know which provider to use from outside (in my app code) and I would have to do it redundantly everywhere where I want to throw this exception. Ideally I would like to declare which provider to use for the exception in the xml.
Ultimately the question can be widened so that instead of exception we think of any runtime object which is not a bean itself.
PS I'm not scared of having hardcoded dependencies to Spring in the code. I use Spring and I want to embrace it - not avoid it.