복붙노트

[SPRING] Spring autowired ... autowired 클래스에 소스 클래스 전달

SPRING

Spring autowired ... autowired 클래스에 소스 클래스 전달

이상한 요구 사항에 휩싸이십시오. 고유 오류 ID를 log4j 메시지에 첨부하고 해당 메시지 ID를 interface.So에 반환해야합니다. 그렇지만 스프링 서비스를 만들 수 있습니다.

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;
   }

  }

이걸 어디서나 필요로 할 때 자동 실행 해 줬어.

 public class LoginLogoutController {

    @Autowired
    LoggingService logger;

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

괜찮 았지만 logger msg의 소스 클래스는 확실한 LoggingService입니다. LoggerService가 autowired 인 클래스를 전달하여 Logger 메시지에 문제의 원래 소스가 표시되도록하는 것이 좋습니다. 나는 어떻게 든 서비스를 바꾸려고 노력했다. 소스 클래스를 어떻게 전달할 지에 대해서는 더 이상 생각하지 못했습니다.

 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;
       }
    }

해결법

  1. ==============================

    1.나는이 메커니즘을 사용하여 로거를 주입했다.

    나는이 메커니즘을 사용하여 로거를 주입했다.

    이 특수 효과를 만듭니다.

    /**
    * 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 {
    }
    

    이제 로거 구현을 주입하는 작업을 실제로 수행하는 클래스를 정의 할 수 있습니다.

    /**
     * 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 필드에 추가하기 만하면됩니다.

    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...");
     }
    }
    
  2. ==============================

    2.Spring AOP를 사용하지 않는 이유는 무엇입니까? AOP는 많은 접근성과 기능을 제공하며 애플리케이션이 무거워지면 나중에 흥미로운 기능을 활용할 수 있습니다. 봄의 AOP

    Spring AOP를 사용하지 않는 이유는 무엇입니까? AOP는 많은 접근성과 기능을 제공하며 애플리케이션이 무거워지면 나중에 흥미로운 기능을 활용할 수 있습니다. 봄의 AOP

  3. from https://stackoverflow.com/questions/25717778/spring-autowired-pass-source-class-to-autowired-class by cc-by-sa and MIT license