#value in spring 5 resolves to default value - spring

#Value in spring 5 resolves to default value even though the property is being loaded from properties
#PropertySource({ "classpath:/config.properties"})
public class ConfigBean {
}
config.properties
com.demo.app.authEnabled=true
Test class
public class Test{
#Value("${com.demo.app.authEnabled:false}")
private boolean authEnabled;
public void method1(){
System.out.println("authEnabled is: "+authEnabled);
}
}
authEnabled is: false
but if I remove the default value of the property it resolves the actual value from the config.properties
#Value("${com.demo.app.authEnabled}")
private boolean authEnabled;
authEnabled is: true

Related

#Value annotation is only loading default - not using property file

Problem
I think that I havn't understood something properly because my #Value is always loading the default calue.
Java Code
So I have the following:
#Value("${disableQuerySecurityDebug:false}")
private boolean disableQuerySecurityDebug;
And this is set to false always.
Property file: application-disableQuerySecurityDebug.properties
I have a properties file called application-disableQuerySecurityDebug.properties.
And I have the following entry inside the file:
disableQuerySecurityDebugMne=true
And I run the application with the following profile: disableQuerySecurityDebugMne
I was expecting the value to be set to true, but it is always false.
Update
Based on deadpool's answer, I ended up with the following:
#Profile("disableQuerySecurityDebug") #Data
#Configuration
public class DisableSecurityConfig implements DisableQuerySecurityDebug {
#Value("${disableQuerySecurityDebug:true}")
private boolean securityDisabled;
}
#Profile("!disableQuerySecurityDebug") #Data
#Configuration
public class EnableSecurityConfig implements DisableQuerySecurityDebug{
#Value("${disableQuerySecurityDebug:false}")
private boolean securityDisabled;
}
public interface DisableQuerySecurityDebug{
public boolean isSecurityDisabled();
}
#Value annotation is only used to inject properties values into spring Beans from yml or properties file
This annotation can be used for injecting values into fields in Spring-managed beans and it can be applied at the field or constructor/method parameter level.
If you want to inject values based on profile specific then use #Profile on class
#Profile("disableQuerySecurityDebug")
#Configuration
public class Config {
#Value("${disableQuerySecurityDebug:false}")
private boolean disableQuerySecurityDebug;
}
You could also specify it on the command line by using the following switch:
java -jar demo.jar --spring.profiles.active=disableQuerySecurityDebug

#Value In Spring MVC is not getting populated

I am trying to populate an attribute using the #Value annotation in Spring MVC, and it is not getting populated.
I am trying to access the attribute using Struts2 JSP property. my use case looks like that:
public class TransferCreditsAction extends StudentAwareAction {
protected Log logger = LogFactory.getLog(this.getClass());
#Value( "${transfer.credit.url}" )
private String transferCreditUrl;
public void setStates( List<TranslatedValue> states ) {
this.states = states;
}
#Value( "${transfer.credit.url}" )
public String getTransferCreditUrl() {
return transferCreditUrl;
}
}
My property file looks like:
transfer.credit.url
I am accessing this attribute using JSP which looks like:
<s:property value='transferCreditUrl'/>"
I know for a fact that my JSP can access this field, because I tested it when I have this field set for a default value.
However, this field is not getting populated from my property file. I am using Spring 4.1.6
Any help is really appreciated.
Spring can only inject values in its own managed spring beans. That means your TransferCreditsAction should be a spring bean.
There are various ways to declare your TransferCreditsAction class as a spring bean, already answered elsewhere.
You haven't added whats on top of TransferCreditsAction class.
Values will be injected in a Bean Env.
There are many ways of Doing it
Assuming my property file contains
username=Ashish
app.name=Hello
1.
#Service
#PropertySource(value = { "classpath:sample.properties" })
public class PaloAltoSbiClientImpl implements PaloAltoSbiClient {
public static String username;
#Value("${username}")
public void setUrl(String data) {
username = data;
}
...
2.
#Service
public class PaloAltoSbiClientImpl implements PaloAltoSbiClient {
#Value("${username}")
public static String username;
...
3.
#Component
public class TokenHelper {
#Value("${app.name}")
private String APP_NAME;
Just give the properties file reference on top of the class in which you are trying to get.
#PropertySource(value = { "classpath:sample.properties" })
This issue was happening because I was missing <context:annotation-config/> in my applicationContext. Once I added it, it start working with no issues.

Can I exclude a specific property from auto configuration

I'm using spring-boot and trying to use "PropertySourcesPlaceholderConfigurer" to load external properties files from filesystem,
but I got an error like below:
Binding to target org.springframework.boot.autoconfigure.web.ServerProperties#3ec11999 failed:
Property: server.environment
Value: BETA
Reason: Failed to convert property value of type [java.lang.String] to required type [org.springframework.core.env.Environment] for property 'environment'; ...
This is because spring-boot tries to auto-config "ServerProperties" and "ServerProperties" looks like:
#ConfigurationProperties(prefix = "server", ignoreUnknownFields = true)
public class ServerProperties
implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered {
...
private Environment environment;
...
}
So it tries to "parse" any property with a "server" prefix.
Unfortunately our legacy properties file happens to contain an irrelevant property called
server.environment=BETA
So spring-boot tries to convert string "BETA" to an "Environment" object.
Is there a way that I can exclude "server.environment" from spring-boot's autoconfigure ?
I don't think you can exclude single property, but you can make trick Spring Boot to preserve original Environment object while converting String to Environment.
#Component
#ConfigurationPropertiesBinding
class OriginalEnvironmentPreservingStringToEnvironmentConverter implements GenericConverter {
private static final Set<ConvertiblePair> CONVERTIBLE_TYPES;
static {
Set<ConvertiblePair> types = new HashSet<>();
types.add(new ConvertiblePair(String.class, Environment.class));
CONVERTIBLE_TYPES = Collections.unmodifiableSet(types);
}
private final Environment environment;
public OriginalEnvironmentPreservingStringToEnvironmentConverter(Environment environment) {
this.environment = environment;
}
#Override
public Set<ConvertiblePair> getConvertibleTypes() {
return CONVERTIBLE_TYPES;
}
#Override
public Object convert(final Object o, final TypeDescriptor typeDescriptor, final TypeDescriptor typeDescriptor1) {
return environment;
}
}
I am not sure if there wouldn't be any side effects though. In simple scenario it does work fine.

How to use systemproperties to get property by using Spring EL and #Value()

#Configuration
#PropertySource("classpath:test.properties")
public class Config {
#Bean
public CompactDisc cd(#Value("#{ systemProperties['artist']}") String artist) {
HotelCalifornia hotelCalifornia = new HotelCalifornia();
hotelCalifornia.setArtist( artist);
return hotelCalifornia;
}
#Bean
public CdPlayer player(CompactDisc cd) {
CdPlayer player = new CdPlayer();
player.setCd(cd);
return player;
}
}
The property is in the test.properties file. I cant get the property "artist" from the systemProperties.But I can get it if i use #autowired to instantiate a environment bean.How can i deal with it?
you dont have to do anything. the spring recognizes property is first it will check in the system properties, then the class level properties and then properties initialized using property placeholder.
so try using #Value("${artist}") provided you have artist set in the systems property somehow.

NullPointerException in EnumMap when auto generating wadl with Jersey

I am using Tomcat 7, Jaxb2 and Jersey1.11.
I have a class EnumProperty which inherits from an abstract class Property.
#XmlAccessorType(XmlAccessType.FIELD)
public class EnumProperty extends Property<Enum> {
#XmlElement(name = "property_value", nillable = true)
private Enum value;
public EnumProperty() {
setValueType(PropertyValueTypeEnum.ENUM);
}
#Override
public Enum getValue() {
return value;
}
#Override
public void setValue(Enum value) {
this.value = value;
}
}
There are other sub classes for the Property class. In addition, I have another class, Entity, which holds a collection of properties. I have also a resource which returns in one of its sub resources a Collection. When I try to generate my application wadl I receive a NullPointerException. I isolated the problem to the EnumProperty class. Can anyone please help me understand where the problem is?
java.lang.NullPointerException
java.util.EnumMap.<init>(Unknown Source)
com.sun.xml.bind.v2.model.impl.RuntimeEnumLeafInfoImpl.<init>(RuntimeEnumLeafInfoImpl.java:87)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.createEnumLeafInfo(RuntimeModelBuilder.java:109)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.createEnumLeafInfo(RuntimeModelBuilder.java:85)
com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:228)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:104)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:85)
com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:213)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:99)
com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:85)
com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:319)
com.sun.xml.bind.v2.model.impl.TypeRefImpl.calcRef(TypeRefImpl.java:96)
com.sun.xml.bind.v2.model.impl.TypeRefImpl.getTarget(TypeRefImpl.java:73)
com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:62)
com.sun.xml.bind.v2.model.impl.RuntimeTypeRefImpl.getTarget(RuntimeTypeRefImpl.java:55)
com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:78)
com.sun.xml.bind.v2.model.impl.ElementPropertyInfoImpl$1.get(ElementPropertyInfoImpl.java:81)
java.util.AbstractList$Itr.next(Unknown Source)...

Resources