2017-04-04 7 views
3

나는 CustomInjections 문서를 따르지 만 log4j2에 대한 업데이트를 시도했습니다. InjectLogger 클래스가 누락 된 것 같습니다.log4j2에 대한 CustomInjections

내가 놓친 아이디어가 있습니까? 아니면 누군가가 실제로 볼 수있는 예제가 있습니까?

답변

2

InjectLogger은 본인이 정의한 맞춤형 주석 유형입니다.

여기 간단한 예제 :

Log4j2CustomInjection.java

package test.guice; 

import com.google.inject.AbstractModule; 
import com.google.inject.Guice; 
import com.google.inject.Injector; 
import com.google.inject.matcher.Matchers; 

public class Log4j2CustomInjection { 

    public static void main(String[] args) { 
    Injector injector = 
     Guice.createInjector(
      new AbstractModule() { 
       @Override 
       protected void configure() { 
       bind(PaymentService.class).asEagerSingleton(); 
       bindListener(Matchers.any(), new Log4JTypeListener()); 
       } 
      }); 

    PaymentService ps = injector.getInstance(PaymentService.class); 
    ps.logger.info("hello"); 
    } 
} 

PaymentService.java

package test.guice; 

import org.apache.logging.log4j.Logger; 

public class PaymentService { 
    @InjectLogger Logger logger; 
} 

InjectLogger.java

package test.guice; 

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.FIELD}) 
public @interface InjectLogger {} 

Log4JTypeListener.java

package test.guice; 

import com.google.inject.TypeLiteral; 
import com.google.inject.spi.TypeEncounter; 
import com.google.inject.spi.TypeListener; 
import java.lang.reflect.Field; 
import org.apache.logging.log4j.Logger; 

class Log4JTypeListener implements TypeListener { 
    public <T> void hear(TypeLiteral<T> typeLiteral, TypeEncounter<T> typeEncounter) { 
    Class<?> clazz = typeLiteral.getRawType(); 
    while (clazz != null) { 
     for (Field field : clazz.getDeclaredFields()) { 
     if (field.getType() == Logger.class && field.isAnnotationPresent(InjectLogger.class)) { 
      typeEncounter.register(new Log4JMembersInjector<>(field)); 
     } 
     } 
     clazz = clazz.getSuperclass(); 
    } 
    } 
} 

Log4JMembersInjector.java

package test.guice; 

import com.google.inject.MembersInjector; 
import java.lang.reflect.Field; 
import org.apache.logging.log4j.LogManager; 
import org.apache.logging.log4j.Logger; 

class Log4JMembersInjector<T> implements MembersInjector<T> { 
    private final Field field; 
    private final Logger logger; 

    Log4JMembersInjector(Field field) { 
    this.field = field; 
    this.logger = LogManager.getLogger(field.getDeclaringClass()); 
    field.setAccessible(true); 
    } 

    public void injectMembers(T t) { 
    try { 
     field.set(t, logger); 
    } catch (IllegalAccessException e) { 
     throw new RuntimeException(e); 
    } 
    } 
}