开发者

Logging exceptions during bean injection

开发者 https://www.devze.com 2022-12-23 19:49 出处:网络
I think this is a pretty basic question, but after Googling around I can\'t seem to find the answer. What I need is a way to log some custom output with log4j during Spring bean construction. I have

I think this is a pretty basic question, but after Googling around I can't seem to find the answer.

What I need is a way to log some custom output with log4j during Spring bean construction. I have a factory class called ResponderFactory (being used as an instance factory in Spring) with a factory method that can throw 2 different types of exception.

    public CollectorResponder collectorResponder(String inputQueueName) throws ConfigurationException, BrokerConnectionException {}

Now, normally I could wrap a call to this me开发者_开发技巧thod in a try-catch block with 2 catch clauses to handle the logging situations for each of the exceptions. However, if I'm using Spring to inject this CollectorResponder, created with the factory, into another class I don't see how this is possible.

<bean id="responderFactory" class="com.package.ResponderFactory">
    <constructor-arg index="0" ref="basicDispatcher" />
    <constructor-arg index="1" value="http://localhost:9000" />
</bean>

<bean id="collectorResponder"
      class="com.package.CollectorResponder"
      factory-bean="responderFactory" factory-method="collectorResponder">
    <constructor-arg value="collector.in" />
</bean>

<bean id="collectorConsumer" class="com.package.CollectorConsumer">
    <constructor-arg ref="collectorResponder" />
</bean>

Again, I want to catch these exceptions when the collectorResponder bean is instantiated. Right now I'm dealing with this is CollectorConsumer when I instantiate using new CollectorResponder(...).

Is there any way I can do this?


I think you are going to need to pass in a different type to the consumer (assuming you want to log errors in the constructor of CollectorConsumer) which is a wrapper around the actual construction of the collectorResponder object. i.e. contains a method like

CollectorResponder create() throws whatever

which is called by your consumer constructor. This wrapper object would be incredibly similar to your factory code but would not be understood by spring. Otherwise, those exceptions are going to happen before your consumer constructor code ever runs no matter what. Spring is not going to be able to inject exceptions, and proxys around an incredibly lazy creation object are unlikely to work without some kind of method call.

I'm assuming that you don't just want to log the exceptions in the responderFactory.

0

精彩评论

暂无评论...
验证码 换一张
取 消