简体   繁体   中英

guice multiple bindings for a single constant

I have a java app that uses guice to do configuration.. I dont think this is what it is intended for but its what has been done and I only need to make a small change so I would prefer not to remove guice. Basically, java properties are bound to variables, I want to bind some to an environmental variables or to a java property. This is what I currently have

bindConstant().annotatedWith(Names.named("value")).to(properties.getProperty("java.property.value"));

this is what I would like to do

bindConstant().annotatedWith(Names.named("value")).to(System.getenv("JAVA_PROPERTY_VALUE"));

Is there a way to combine the two? I cannot do both. Or, is this just a default and I basically have what I need already? ie if I do bindConstant to System.getenv that value will be used unless its overwritten in the properties file (in my case the string constant is not the full property name so I am unsure how it works now).

I really do not know much about how guice works, I believe an injector is created where this code is and later used to do things like...

@Inject(optional = true)
@Named("value)
private String value;

I basically want that value to default to the one in the properties file, but be overridden by the env property value if its present.

I have tried simply using the env var value if it exists otherwise the property value, ie

bindConstant().annotatedWith(Names.named("value")).to(System.getenv(envVarName) != null && !System.getenv(envVarName).trim().isEmpty() ? System.getenv(envVarName) : properties.getProperty(propertyName));

Which works as expected when the environmental variable is defined and the property is not defined, but when both are defined the property is always used. Which just leads me to the fact that I know very little about guice and how it works, I have in code a very explicit binding between the property name and this method, but, it just seems to be a default value, something after that is overwriting my value with the one from the property file.

This is super basic, but it's how we do things:

  • get Properties (sys.properties)

some.random.prop=localhost

  • iterate through System.getEnv() overriding all the Properties
// Convert SOME_RANDOM_PROP to some.random.prop
properties.put(parseKey(entry.getKey()), entry.getValue());

Now your properties should be defaulted to app.properties and overwritten with matching env.properties, then just bind all he properties.

Names.bindProperties(binder(), properties);

The caveat here is that now System.getEnv() pointless, but since you're using Guice for all your injections this shouldn't really be an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM