Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在Guice中为变量设置默认值_Java_Spring_Guice - Fatal编程技术网

Java 如何在Guice中为变量设置默认值

Java 如何在Guice中为变量设置默认值,java,spring,guice,Java,Spring,Guice,就像我们在春天做的那样 @Value("${varName:0}") int varName; 有没有一种方法可以使用GoogleGuice做到这一点?在Guice中,您可以对该方法进行注释并使其成为可选的。然后只需指定默认值。如果没有要注入的属性,它将是默认值 例如: public class TestModule3 extends AbstractModule { @Override protected void configure() { // Proper

就像我们在春天做的那样

@Value("${varName:0}")
int varName;

有没有一种方法可以使用GoogleGuice做到这一点?

在Guice中,您可以对该方法进行注释并使其成为可选的。然后只需指定默认值。如果没有要注入的属性,它将是默认值

例如:

public class TestModule3 extends AbstractModule {

    @Override
    protected void configure() {

//      Properties p = new Properties();
//      p.setProperty("myValue", "12");
//      Names.bindProperties(binder(), p); // this binds the properties that usually come for a file

        bind(Manager.class).to(ManagerImpl.class).in(Singleton.class);
    }

    public static interface Manager {
        public void talk();
    }

    public static class ManagerImpl implements Manager {

        @Inject(optional = true)
        @Named("myValue")
        int test = 0;

        @Override
        public void talk() {
            System.out.println(test);
        }
    }

    public static void main(String[] args) {

        Manager instance = Guice.createInjector(new TestModule3()).getInstance(Manager.class);
        instance.talk();

    }
}
这将为您打印“0”,因为我注释掉了属性绑定。如果删除注释,它会将值12绑定到字符串myValue。InjectAnnotation负责其余部分

希望有帮助

编辑:

正如@TavianBarnes指出的,Guice 4+有一个可选绑定器。我为你的用例尝试了这个,但无法使它开箱即用

OptionalBinding似乎对类(实际实例)非常有用,而不是对属性。原因如下:

  • 您必须提前知道所有属性,并将它们绑定到默认值。很容易忘记它们。OP显示的示例还表明,他不知道是否有可用的属性(基于名称)

  • 属性绑定的默认实现不能与OptionalBinding组合使用

  • 所以你可以这样做:

            OptionalBinder.newOptionalBinder(binder(), Key.get(String.class, Names.named("myValue"))).setDefault()
                    .toInstance("777");
    
            Properties p = new Properties();
            p.setProperty("myValue", "12");
    
            // use enumeration to include the default properties
            for (Enumeration<?> e = p.propertyNames(); e.hasMoreElements();) {
                String propertyName = (String) e.nextElement();
                String value = p.getProperty(propertyName);
    
                OptionalBinder.newOptionalBinder(binder(), Key.get(String.class, Names.named(propertyName))).setBinding()
                        .toInstance(value);
    
            }
    
    这是如何定义默认值的默认注释。 上述财产说明:

  • 使用evnironment变量“ENV_VAR_NAME”
  • 如果未设置“ENV_VAR_NAME”,请使用值“600”
  • 然后我将其绑定如下:

            InputStream resourceAsStream = getClass().getResourceAsStream(path);
            if(resourceAsStream == null) {
                throw new IllegalArgumentException("No property file found for path: " + path);
            }
            try {
                p.load(resourceAsStream);
                EnvironmentVariableSubstitutor envSubstitutor = new EnvironmentVariableSubstitutor(false);
                Set<Object> keys = p.keySet();
                for(Object k : keys) {
                    String property = p.getProperty(k.toString());
                    property = envSubstitutor.replace(property);
                    p.put(k, property);
                }
    
            } catch (IOException e) {
                throw new IllegalStateException("Could not load properties", e);
            } finally {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    log.error("Could not close stream for resource " + path);
                }
            }
    
            Names.bindProperties(binder(), p);
    
    InputStream resourceAsStream=getClass().getResourceAsStream(路径);
    if(resourceAsStream==null){
    抛出新的IllegalArgumentException(“未找到路径:“+path”的属性文件);
    }
    试一试{
    p、 加载(资源流);
    EnvironmentVariableSubstitutor envSubstitutor=新的EnvironmentVariableSubstitutor(false);
    设置键=p.键集();
    用于(对象k:关键点){
    字符串属性=p.getProperty(k.toString());
    property=envSubstitutor.replace(属性);
    p、 put(k,财产);
    }
    }捕获(IOE异常){
    抛出新的IllegalStateException(“无法加载属性”,e);
    }最后{
    试一试{
    resourceAsStream.close();
    }捕获(IOE异常){
    log.error(“无法关闭资源的流”+路径);
    }
    }
    name.bindProperties(binder(),p);
    
    此代码的作用是:

  • 从资源文件加载属性
  • 使用EnvironmentVariableSubstitutor处理属性值并覆盖结果。(参见循环)
  • 最后,将修改的属性绑定到它们的名称
  • 这些都是我能在短时间内想出的解决方案:)如果有什么不清楚的地方,请告诉我

    编辑2:

    有一些关于OptionalBindings和properties的信息,以及如何处理此google线程中的默认值:


    Artur

    对于Guice 4+,您应该使用
    OptionalBinder
    ,而不是
    @Inject(optional=true)
    @TavianBarnes谢谢!我不知道,稍后将更新我的示例。@TavianBarnes我认为OptionalBinding对于您不知道是否存在的属性不是很有用。我用我的想法更新了答案:)不管怎样,很高兴知道我发现有效的一个解决方案-
            InputStream resourceAsStream = getClass().getResourceAsStream(path);
            if(resourceAsStream == null) {
                throw new IllegalArgumentException("No property file found for path: " + path);
            }
            try {
                p.load(resourceAsStream);
                EnvironmentVariableSubstitutor envSubstitutor = new EnvironmentVariableSubstitutor(false);
                Set<Object> keys = p.keySet();
                for(Object k : keys) {
                    String property = p.getProperty(k.toString());
                    property = envSubstitutor.replace(property);
                    p.put(k, property);
                }
    
            } catch (IOException e) {
                throw new IllegalStateException("Could not load properties", e);
            } finally {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    log.error("Could not close stream for resource " + path);
                }
            }
    
            Names.bindProperties(binder(), p);