Paul
Paul

Reputation: 20081

Why is my custom annotation logging bean null during autowiring?

I created a custom annotation for logging following the example in this blog post almost exactly. The main difference that I can see is my LoggerInjector is annotated with @Component.

The annotation works great and I get a non-null Logger instance everywhere except in one case: when I try to log in a method annotated with @Autowired.

For example:

@Repository
public class MyDao
{
    @AutowiredLogger
    private Logger _logger;

    private JdbcTemplate _jt;

    @Autowired
    public void setDatasource(DataSource ds)
    {
        _logger.debug("Entering setDs")
        _jt = new JdbcTemplate(ds);
        _logger.debut("Exiting setDs);
    }
}

A NullPointerException is thrown on the first _logger.debug() line.

A snippet from applicationContext.xml:

<mvc:annotation-driven />
<context:component-scan base-package="my.package" />

A snippet from dispatch-servlet.xml:

<mvc:annotation-driven />
<context:component-scan base-package="my.package">
    <context:include-filter type="annotation"
             expression="org.springframework.stereotype.Repository" />
</context:component-scan>

How can I have my @AutowiredLogger injected before the @Autowired methods are run?

Upvotes: 1

Views: 523

Answers (1)

Amir Raminfar
Amir Raminfar

Reputation: 34169

I don't think you can control which component gets autowired first. An alternate solution is to use InitializingBean to configure the class after everything has been set.

You could something like

@Override
void afterPropertiesSet() {
    _logger.debug("Entering setDs")
    _jt = new JdbcTemplate(ds);
    _logger.debut("Exiting setDs);
}

Upvotes: 4

Related Questions