Set Null For a String Property by Value in Spring

Set a null value for a field of type String in the @Value annotation

In Spring, you can use @Value to set default values for the parameters of field, method, method / constructor.
However, how to set a null value for a string type field?

The following methods are all wrong:

@Value(${app.name1:})
private String name1;
@Value(${app.name2:''}) private String name2;
@Value(${app.name3:null}) private String name3;

1. @Value

Let’s take a look at how to use @Value annotation first. It is mainly used to inject values for parameters of fields or methods / constructors.
public static class FieldValueTestBean{
@Value("#{ systemProperties[''user.region''] ?: 'en_US'" }") private String defaultLocale;
@Value("${user.name}") private String userName;
public void setDefaultLocale(String defaultLocale) { this.defaultLocale = defaultLocale;
}
public String getDefaultLocale() { return this.defaultLocale;
} }
It can also be placed on the method as shown below:
public static class PropertyValueTestBean{
private String defaultLocale;
@Value("#{ systemProperties[''user.region''] }") public void setDefaultLocale(String defaultLocale) { this.defaultLocale = defaultLocale; }
public String getDefaultLocale() { return this.defaultLocale; } }
Even on the constructor:
public class MovieRecommender {
private String defaultLocale; private CustomerPreferenceDao customerPreferenceDao;
@Autowired public MovieRecommender(CustomerPreferenceDao customerPreferenceDao, @Value("#{systemProperties[''user.country'']}") String defaultLocale) { this.customerPreferenceDao = customerPreferenceDao; this.defaultLocale = defaultLocale; }
}

It supports two expressions:

Placeholder way. The default is to use the $ {…} method, placeholder in braces.
Spring Expression Language. The format is # {…}, Spring EL expression in parentheses. Specific reference can check Spring Language Reference

1.1 Default value

If there is no placeholder or the expression is empty, we can provide a default value.
${property:default value}
Example:
@Value("${mongodb.url:127.0.0.1}")
private String mongodbUrl;
@Value("#{'${mongodb.url:172.0.0.1}'}") //Mixed Mode private String mongodbUrl;
@Value("#{config['mongodb.url']?:'127.0.0.1'}") //Mixed mode + default private String mongodbUrl;

2. Spring EL Method

#{expression?:default value}

Example:

@Value("#{systemProperties['onlinetutorials.url'] ?: localhost:2181}")
private String zookeeperUrl;
@Value("#{config['mongodb.url'] ?: '127.0.0.1:27017'}") private String mongodbUrl;
@Value("#{user.age ?: 18}") private int age;

3. String null

If the configured attribute, we want to set a default value of null, how to do it?
Two ways:

3.1 Spring EL Method

@Value("${app.name:#{null}}")
privateString name;

3.2 PlaceHolder way

In this way, the property nullValue needs to be set for PlaceholderConfigurerSupport or its subclasses, for example:
placeholderConfigurer.setNullValue("@null");
So the string @null represents the null object.
@Value("${app.name:@null}")
private String name;
It can also be set in the properties file:
app.name=@null

4. Complete test Example:

App.java

package com.onlinetutorials.tech;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");
HelloService service = (HelloService)ctx.getBean("helloService");
service.test();
}
}

AppConfig.java

package com.onlinetutorials.tech;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@PropertySource("classpath:/application.properties")
@Configuration
public class AppConfig{
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() throws Exception {
PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
placeholderConfigurer.setNullValue("@null");
return placeholderConfigurer;
}
}

HelloService.java

package com.onlinetutorials.tech;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Service
public class HelloService{
@Value("${app.count}")
private int num;
@Value("${app.name1:abcd}")
private String name1;
@Value("${app.name2:`abcd`}")
private String name2;
@Value("${app.name3}")
private String name3;
@Value("${app.enable}")
private boolean appEnable;
@Value("${app.name4:}")
private String name4;
@Value("${app.name5:''}")
private String name5;
@Value("${app.name6:@null}")
private String name6;
@Value("${app.name7:#{null}}")
private String name7;
@PostConstruct
public void start() {
System.out.println("start");
}
public void test(){
System.out.println("num=" + num);
System.out.println("appEnable=" + appEnable);
System.out.println("name1=" + name1);
System.out.println("name2=" + name2);
System.out.println("name3 =" + name3);
System.out.println("name4 =" + name4);
System.out.println("name5 = " + name5);
System.out.println("name6 = " + name6);
System.out.println("name7 = " + name7);
}
@PreDestroy
public void stop(){
System.out.println("stop");
}
}

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"
default-autowire="byType">
<context:annotation-config />
<context:component-scan base-package="com.onlinetutorials.tech"/>
<util:properties id="configProperties" location="classpath:application.properties"/>
<context:property-placeholder properties-ref="configProperties" ignore-resource-not-found="true"/>
</beans>

application.properties

app.count=0
app.name3=@null
app.enable=false
%d bloggers like this: