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

Asked

Viewed 364 times

1

I am configuring two Beans in the file beans.xml 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 makes the method LoggerFactory.createLogger be called and this is working properly.

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

3 answers

1

I have never seen injecting log class this way. I see no 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 by the method Factory, thus:

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

The very log4j documentation on the architecture points this way to recover Loggers, and the same instance will be recovered whenever the method parameter getLogger be the same.

0

I’m not versed in Spring ways, but why not just inject the LoggerFactory and create the Logger in your bean builder.

I mean, 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, given that loggers, in theory, are thread-safe, nor use dependency injection.

public class MeuBean {

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

}

0

I don’t know what it would be like in Spring, but with the CDI standard it would be like this:

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

You can then consume so:

@Inject
Logger logger;
  • I’ve worked with CDI, and that’s why I asked this question. I know it’s possible that way, but in Spring I don’t know how to do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.