2014-06-12 5 views
6

मेरे पास कुछ संसाधन है, लेकिन मैं इसे पुन: सक्रिय नहीं कर सकता और उन्हें सभी को बाध्य नहीं कर सकता, मुझे संसाधन का अनुरोध करने के लिए कुंजी का उपयोग करना होगा। इसलिए, मुझे गतिशील इंजेक्ट करना है।कस्टम एनोटेशन के साथ गतिशील इंजेक्शन

मैं इस तरह

public class Test 
{ 
    @Inject 
    @Res("author.name") 
    String name; 
    @Inject 
    @Res("author.age") 
    int age; 
    @Inject 
    @Res("author.blog") 
    Uri blog; 
} 

मैं इंजेक्शन @Res द्वारा एनोटेट को संभालने के लिए है की तरह

@Target({ METHOD, CONSTRUCTOR, FIELD }) 
@Retention(RUNTIME) 
@Documented 
@BindingAnnotation 
public @interface Res 
{ 
    String value();// the key of the resource 
} 

उपयोग एक एनोटेशन को परिभाषित करने और मैं इंजेक्षन क्षेत्र और एनोटेशन जानना चाहते हैं।

क्या यह Guice में और कैसे संभव है? स्पि के साथ भी?

+0

के संभावित डुप्लिकेट की तरह CustomInjections

कोड का पालन https://stackoverflow.com/questions/5704918/custom-guice-binding-annotations-with-parameters और https : //stackoverflow.com/questions/41958321/guicebinding-annotations-with-attributes – Phil

उत्तर

3

मैं बाहर काम इस

public class PropsModule extends AbstractModule 
{ 
    private final Props props; 
    private final InProps inProps; 

    private PropsModule(Props props) 
    { 
     this.props = props; 
     this.inProps = InProps.in(props); 
    } 

    public static PropsModule of(Props props) 
    { 
     return new PropsModule(props); 
    } 

    @Override 
    protected void configure() 
    { 
     bindListener(Matchers.any(), new TypeListener() 
     { 
      @Override 
      public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) 
      { 
       Class<? super I> clazz = type.getRawType(); 
       if (!clazz.isAnnotationPresent(WithProp.class)) 
        return; 
       for (Field field : clazz.getDeclaredFields()) 
       { 
        Prop prop = field.getAnnotation(Prop.class); 
        if (prop == null) 
         continue; 

        encounter.register(new PropInjector<I>(prop, field)); 
       } 
      } 
     }); 
    } 

    class PropInjector<T> implements MembersInjector<T> 
    { 
     private final Prop prop; 
     private final Field field; 

     PropInjector(Prop prop, Field field) 
     { 
      this.prop = prop; 
      this.field = field; 
      field.setAccessible(true); 
     } 

     @Override 
     public void injectMembers(T instance) 
     { 
      try { 
       Class<?> targetType = field.getType(); 
       Object val = inProps.as(prop.value(), targetType); 
       field.set(instance, val); 
      } catch (IllegalAccessException e) { 
       throw new RuntimeException(e); 
      } 
     } 
    } 
} 
संबंधित मुद्दे