Spring autowired ...将源类传递给autowired类 [英] Spring autowired...pass source class to autowired class

查看:103
本文介绍了Spring autowired ...将源类传递给autowired类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

陷入了一个奇怪的要求.我需要在log4j消息上附加唯一的错误ID,然后将该消息ID返回到接口.因此,尽管如此,我还是创建了一个Spring服务,像这样

Caught up in a weird requirement. I need to attach unique error id to log4j message and return that message id back to interface.So, I though lets create a spring service, like this

public class LoggingService {

   protected static Logger logger = LoggerFactory.getLogger(LoggingService.class);



   public String debug(String debug_msg)
   {
       String uniqueMsgId = generateUniqueId();
       logger.debug(concatIdWithMsg(uniqueMsgId, debug_msg));
       return uniqueMsgId;
   }

  }

并将其自动接线到我需要的地方.

and autowired this to wherever i need it.

 public class LoginLogoutController {

    @Autowired
    LoggingService logger;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String getLoginPage()
    {
       logger.debug("Login page requested");
    }
    }

尽管工作正常,但记录器msg中的源类是LoggingService,这很明显.我想要的是传递LoggingService自动连接的类,以便记录器消息显示问题的原始来源.我试图以某种方式更改服务 但不知道如何传递源类

Although it worked fine, but the source class in logger msg is LoggingService which is obvious. What i want is to pass the class in which LoggingService is autowired so that the logger message shows the original source of problem. I tried somehow to change the service but got no further idea how to pass source class

 public class LoggingService<T> {

       protected static Logger logger = null;

       Class<T> sourceClass;

       public void construct(Class<T> sourceClass)
       {
           this.sourceClass = sourceClass;
           logger = LoggerFactory.getLogger(sourceClass);
       }

       public String debug(String debug_msg)
       {
           String uniqueMsgId = generateUniqueId();
           logger.debug(concatIdWithMsg(uniqueMsgId, debug_msg));
           return null;
       }
    }

推荐答案

我使用了这种机制来注入记录器.

I used this mechanism to inject a logger.

创建此注释.

/**
* Indicates InjectLogger of appropriate type to
* be supplied at runtime to the annotated field.
*
* The injected logger is an appropriate implementation
* of org.slf4j.Logger.
*/
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(FIELD)
@Documented
public @interface InjectLogger {
}

现在,让我们定义一个实际完成注入记录器实现工作的类.

Now lets define a class that actually does the job of injecting the logger implementation.

/**
 * Auto injects the underlying implementation of logger into the bean with field
 * having annotation <code>InjectLogger</code>.
 * 
 */
import java.lang.reflect.Field;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;

import static org.springframework.util.ReflectionUtils.FieldCallback;

public class LoggerInjector implements BeanPostProcessor {

 public Object postProcessAfterInitialization(Object bean, String beanName)
   throws BeansException {
  return bean;
 }

 public Object postProcessBeforeInitialization(final Object bean,
   String beanName) throws BeansException {
  ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
   public void doWith(Field field) throws IllegalArgumentException,
     IllegalAccessException {
    // make the field accessible if defined private
    ReflectionUtils.makeAccessible(field);
    if (field.getAnnotation(InjectLogger.class) != null) {
     Logger log = LoggerFactory.getLogger(bean.getClass());
     field.set(bean, log);
    }
   }
  });
  return bean;
 }
}

使用它甚至更简单.只需将上面创建的Logger批注添加到所需类的Log字段中即可.

Using it is even simpler. Just add the Logger annotation created above to the Log field in the required class.

import org.slf4j.Logger;

public class Demo {

 @InjectLogger
 private Logger log;

 public void doSomething() {
  log.info("message");
  log.error("Lets see how the error message looks...");
 }
}

这篇关于Spring autowired ...将源类传递给autowired类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆