Search code examples
javaspringdependency-injectionjava-ee-6

Autowiring email sender bean into another bean?


I am using spring 3.x version and am using annotations to wire the dependencies. I have two beans as below.

package com.sample.project.service;
@Component
public class MyAppender extends AppenderSkeleton{


     //here trying to inject emailSender bean
    @Autowired
    private EmailSender emailSender;

//some code with emailSender
//emailSender.callSomeService...


}

Above bean extends AppenderSkeleton class of log4j.

package com.sample.project.service;
@Component
public class EmailSender {

  @Autowired
  private SomeOtherBean someOther;

//somecode

}

I have an entry in applicationContext.xml as below.

<context:component-scan base-package="com.sample.project.service" />

Log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

    <!-- Appenders -->

    <appender name="stdout" class="com.sample.project.service.MyAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %p [%c] - %m%n"/>
        </layout>
    </appender>


    <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
        <param name="BufferSize" value="500"/>
        <appender-ref ref="stdout"/>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="ASYNC" />
    </root>

</log4j:configuration>

But the problem is, emailSender injected into MyAppender is always null. Am i doing anything wrong here. Or is there any problem with overriding log4jspecific classes and annotating them with @Component ? Thanks! Please help me!


Solution

  • With this config

    <appender name="stdout" class="com.sample.project.service.MyAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d %p [%c] - %m%n"/>
        </layout>
    </appender>
    

    log4j is creating its own MyAppender instance. This instance has nothing to do with the @Component instance that Spring creates. As such, there is no autowiring being done and your field is initialized to null by default.