Spring @Value注解设置变量默认值

x33g5p2x  于2022-09-23 转载在 Spring  
字(5.7k)|赞(0)|评价(0)|浏览(1230)

Spring @Value 注解用于表达式驱动的依赖注入。 @Value 可以配置在实际值不可用于依赖注入时使用的默认值。 @Value 使用 ${...}#{...} 语法来编写表达式。
1.${...} 是一种属性占位符语法。我们需要使用冒号 (:) 来指定默认值。

@Value("${cp.user.name:Shree Mahesh}")
private String userName;

2.#{...} 是一种 SpEL 语法。它还可以处理属性占位符等等。我们需要使用 Elvis Operator (?:) 来指定默认值。

@Value("#{systemProperties['unknown_prop_key'] ?: 'Default System Value'}") 
private String mySystemVal;

我们使用在 JavaConfig 中注释的 @PropertySource 读取属性文件,并使用 @Value 注释解决依赖注入。在这里,我们将讨论使用 @Value 为字符串、布尔值、整数、列表和映射类型字段指定默认值。

1. 字符串默认值

为了解决使用 @Value 的依赖注入,我们使用 ${...}#{...} 语法来编写表达式。
1. 我们需要使用冒号 (:) 来使用 ${...} 语法指定默认值。假设我们有一个属性文件 myproject.properties 文件。在我们的 JavaConfig 中,我们读取带有 @PropertySource 注释的属性文件。

@Configuration
@PropertySource("classpath:myproject.properties")
public class AppConfig {
  @Value("${cp.user.name:Shree Mahesh}")
  private String userName;
 ------
}

当属性文件中没有定义 cp.user.role 属性时,默认值 Shree Mahesh 将被注入到 userName 字段中。要使用 ${...} 语法指定默认值,我们不需要用单引号 ('') 将默认值括起来。
如果我们在 : 之后为默认值添加一个空格,那么它将包含在默认值中。如果我们在 } 之前为默认值添加一个空格,它也将包含在默认值中。查看以下代码片段。
一个。没有空格作为前缀和后缀。

${cp.user.name:Shree Mahesh}

湾。空格作为前缀。空间将计入默认值。

${cp.user.name: Shree Mahesh}

C。空格作为前缀和后缀。空格将计入默认值。

${cp.user.name: Shree Mahesh }

2. 如果我们想从属性文件中选择默认值,那么我们可以使用如下的 ${...} 语法。

@Value("${cp.user.role:${cp.user.role.default}}")
private String userRole;

当属性文件中没有定义 cp.user.role 属性时,默认值将被注入到 userRole 中,从 cp.user.role.default 属性中选择它。

3. 要使用 #{...} SpEL 语法指定默认值,我们需要使用 Elvis Operator (?:),如下所示。

@Value("#{systemProperties['unknown_prop_key'] ?: 'Default System Value'}") 
private String mySystemVal;

在上面的代码片段中,对于演示,我们尝试从系统属性中获取未知键的值。由于该值将为空,因此默认值将被注入 mySystemVal

2. 布尔默认值

要指定布尔默认值,请查找代码片段。

@Value("${cp.user.active:true}")
private Boolean isUserActive;

当属性文件中没有定义 cp.user.active 属性时,true 将被注入到 isUserActive 中。

3. 整数默认值

要指定整数默认值,请查找代码片段。

@Value("${cp.user.age: 30}")
private Integer userAge;

当属性文件中没有定义 cp.user.age 属性时,30 将被注入到 userAge 中。

4. 数组默认值

要注入默认数组,我们可以使用 ${...} 语法,如下所示。

@Value("${cp.user.skills:Java,Spring,Angular}")	
private String[] userSkills;

当属性文件中没有定义 cp.user.skills 属性时,默认数组将被注入到 userSkills
同样,我们也可以注入原始数据类型整数数组作为默认值。

@Value("${cp.user.skillids:5,6,7}")		
private int[] userSkillIds;

5. List默认值

要注入默认列表值,我们可以使用 #{...} SpEL 语法和 ${...} 语法,如下所示。

@Value("#{'${cp.user.skills:Java,Spring,Angular}'.split(',')}") 
private List<String> userSkills;

当属性文件中没有定义 cp.user.skills 属性时,默认列表将被注入到 userSkills

6. Map默认值

要注入默认Map,我们可以使用 #{...} SpEL 语法。

@Value("#{${cp.user.teamMates: {100: 'Krishna', 200: 'Shiva'}}}")
private Map<Integer, String> teamMates;

当属性文件中没有定义 cp.user.teamMates 属性时,默认列表将被注入到 teamMates

7. 默认空

要将 null 值指定为默认值,我们可以指定 #{null} 如下。

@Value("${cp.user.country:#{null}}")
private String userCountry;

当属性文件中没有定义 cp.user.country 时,userCountry 将被注入 null 值。

完整示例

AppConfig.java

package com.concretepage;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:myproject.properties")
public class AppConfig {
	 //Default String
	 @Value("${cp.user.name:Shree Mahesh}")
	 private String userName;
	 
	 @Value("${cp.user.role:${cp.user.role.default}}")
	 private String userRole;
	 
	 @Value("${cp.user.country:India}")
	 private String userCountry;
	 
	 //Default Boolean
	 @Value("${cp.user.active:true}")
	 private Boolean isUserActive;
	 
	 //Default Integer
	 @Value("${cp.user.age: 30}")
	 private Integer userAge;	 

	 //Default using SpEL with Elvis Operator (?:)
	 @Value("#{systemProperties['unknown_prop_key'] ?: 'Default System Value'}") 
	 private String mySystemVal;	 
	 
	 //Default for List
	 @Value("#{'${cp.user.skills:Java,Spring,Angular}'.split(',')}") 
	 private List<String> userSkills;
	 
	 //Default for Map
	 @Value("#{${cp.user.teamMates: {100: 'Krishna', 200: 'Shiva'}}}")
	 private Map<Integer, String> teamMates;
	 
	 @Bean
	 public User getUser() {
		 User user = new User();
		 user.setUserName(userName);
		 user.setUserRole(userRole);
		 user.setUserCountry(userCountry);
		 user.setUserActive(isUserActive);
		 user.setUserAge(userAge);
		 user.setMySystemVal(mySystemVal);
		 user.setUserSkills(userSkills);
		 user.setTeamMates(teamMates);
		 return user;
	 }
}

myproject.properties

cp.user.country= USA
cp.user.role.default= Contributor

User.java

package com.concretepage;
import java.util.List;
import java.util.Map;
public class User {
	private String userName;
	private String userRole;
	private String userCountry;
	private Boolean userActive;
	private Integer userAge;
	private String mySystemVal;
	private List<String> userSkills;
	private Map<Integer, String> teamMates;
        //Setters and Getters
}

build.gradle

apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'spring-demo'

repositories {
    mavenCentral()
}
dependencies {
    compile  'org.springframework.boot:spring-boot-starter:2.1.4.RELEASE'
}

MySpringApp.java

package com.concretepage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MySpringApp {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.scan("com.concretepage");
		ctx.refresh();
		User user = ctx.getBean(User.class);
		
		System.out.println("userName: " + user.getUserName());
		System.out.println("userRole: " + user.getUserRole());
		System.out.println("userCountry: " + user.getUserCountry());
		System.out.println("userActive: " + user.getUserActive());
		System.out.println("userAge: " + user.getUserAge());
		System.out.println("mySystemVal: " + user.getMySystemVal());
		System.out.println("userSkills: " + user.getUserSkills());
		System.out.println("teamMates: " + user.getTeamMates());
		
		ctx.registerShutdownHook();
		ctx.close();
	}
}

输出

userName: Shree Mahesh
userRole: Contributor
userCountry: USA
userActive: true
userAge: 30
mySystemVal: Default System Value
userSkills: [Java, Spring, Angular]
teamMates: {100=Krishna, 200=Shiva}

相关文章

微信公众号

最新文章

更多