当前位置:网站首页>Set a null value for a field of type string in the @ value annotation

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

2021-10-22 10:29:34 Bird's nest

stay Spring Can be used in @Value by fieldmethodmethod/constructor The default value of the parameter setting is .
however , If how to set... For a string type field null Is it worth it ?
The following methods are all wrong :

       
       
       
1
2
3
4
5
6
7
8
       
       
       
@Value( "${app.name1:}")
private String name1;
@Value( "${app.name2:''}")
private String name2;
@Value( "${app.name3:null}")
private String name3;

@Value

Let's take a look first @Value How to use annotations . It is mainly used for Field perhaps Method / Constructors Parameters of Injection value .

       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
       
       
       
public static class FieldValueTestBean
@Value("#{ systemProperties[''user.region''] ?: 'zh_CN'" }")
private String defaultLocale;
@Value("${user.name}")
private String userName;
public void setDefaultLocale(String defaultLocale) {
this.defaultLocale = defaultLocale;
}
public String getDefaultLocale() {
return this.defaultLocale;
}
}

You can also put it on the method :

       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
       
       
       
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 constructors :

       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
       
       
       
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 The way . By default ${...} The way , In curly braces placeholder.
  • Spring Expression Language The way . The format is #{...}, In brackets Spring EL expression . For details, please refer to Spring Language Reference

The default value

without placeholder Or the expression is empty , We can provide a default value .

  1. PlaceHolder The way
       
       
       
1
       
       
       
$ {property:default value}

for example

       
       
       
1
2
3
4
5
6
7
8
       
       
       
@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 + The default value
private String mongodbUrl;

This example is taken from : mkyong

  1. Spring EL The way
       
       
       
1
       
       
       
#{ expression?:default value}

for example

       
       
       
1
2
3
4
5
6
7
8
       
       
       
@Value( "#{systemProperties['zookeeper.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;

character string null

If the configured properties , We want to set up a null Default value , How to do it ?
Two ways :

  1. Spring EL The way
       
       
       
1
2
       
       
       
@Value( "${app.name:#{null}}")
private String name;
  1. PlaceHolder The way
    This approach needs to be PlaceholderConfigurerSupport Or its subclasses set properties nullValue, such as :
       
       
       
1
       
       
       
placeholderConfigurer.setNullValue( "@null");

So the string @null On behalf of null object .
You can

       
       
       
1
2
       
       
       
@Value( "${app.name:@null}")
private String name;

You can also set... In the properties file :

       
       
       
1
       
       
       
app. name=@ null

Complete test code

  • App.java
       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
       
       
       
package com.colobu.spring;
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
       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
       
       
       
package com.colobu.spring;
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
       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
       
       
       
package com.colobu.spring;
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
       
       
       
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
       
       
       
<?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.colobu.spring"/>
<util:properties id="configProperties" location="classpath:application.properties"/>
<context:property-placeholder properties-ref="configProperties" ignore-resource-not-found="true"/>
</beans>
  • application.properties
       
       
       
1
2
3
       
       
       
app. count= 0
app. name3=@ null
app. enable= false

版权声明
本文为[Bird's nest]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/10/20211009000611420t.html