How to get the name of the class where a bean will be injected?

1

I'm setting two beans in the beans.xml file to inject loggers into my classes.

<bean id="loggerFactory" class="company.LoggerFactory" />
<bean id="logger" class="org.apache.log4j.Logger" factory-bean="loggerFactory" factory-method="createLogger" />

The setting causes the LoggerFactory.createLogger method to be called and this is working correctly.

What I want to know is: how within this method, do I get the class where the object will be injected to put it as the logger name?

    
asked by anonymous 06.02.2014 / 20:02

3 answers

1

I've never seen injecting log class like this. I do not see any need to inject the log, since there should be an instance for the class.

Just create a logger for each class in a private attribute using the factory method, like this:

public class MinhaClasse {
    private final Logger log = Logger.getLogger(MinhaClasse.class);
    (...)
}

The log4j documentation on architecture points to this way to retrieve loggers, and the same instance will be retrieved whenever the parameter of the getLogger method is the same.

    
06.02.2014 / 20:14
0

I'm not versed in Spring manners, but why not inject only LoggerFactory and create Logger in your bean's constructor.

That is, something like:

public class MeuBean {

  private final Logger logger;

  public MeuBean(LoggerFactory factory) {
     this.logger = factory.getLogger(getClass());
  }    

}

Surely there must be a more 'Spring' way to directly inject the Logger instance with the settings you want, but in theory this should work.

Or, since Loggers, in theory, are thread safe, nor use dependency injection.

public class MeuBean {

  private static final Logger logger = LoggerFactory.getLogger(MeuBean.class);

}
    
06.02.2014 / 20:17
0

I do not know what Spring would look like, but with the default CDI it would look like this:

@Produces
public static Logger produceLog(InjectionPoint injectionPoint) {
  return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
}

You can then consume like this:

@Inject
Logger logger;
    
07.02.2014 / 15:57