@Value取值为NULL怎么办,解决方案有哪些

@Value取值为NULL的问题

在spring mvc架构中,如果希望在程序中直接使用properties中定义的配置值,通常使用一下方式来获取:

    @Value("${tag}")
    private String tagValue;

但是取值时,有时这个tagvalue为NULL,可能原因有:

使用static或final修饰了tagValue,如下:

    private static String tagValue;  //错误
    private final String tagValue;    //错误

类没有加上@Component(或者@service等)

    @Component   //遗漏
    class TestValue{
    
    
         @Value("${tag}")
         private String tagValue;
    }

类被new新建了实例,而没有使用@Autowired

   @Component   
    class TestValue{
    
    
         @Value("${tag}")
         private String tagValue;
    }
    class Test{
    
    
        ...
        TestValue testValue = new TestValue()
    }

这个testValue中肯定是取不到值的,必须使用@Autowired:

class Test{
    
    
        @AutoWired
        TestValue testValue
    }

@Value取值为NULL原因分析

有两种方式:

  • @Value(“${}”)用于获取配置文件中的属性值,通常用于获取写在application.properties中的内容;
  • @Value(“#{}”) 其实是SpEL表达式的值,可以表示常量的值,或者获取bean中的属性

区别:

  • ① ${ property : default_value } //property对应外部配置文件,default_value,就是前面的值为空时的默认值。
  • ② #{ obj.property? :default_value } //SpEL表达式,obj代表对象

一.@Value(“${}”)的使用

 @Value("${inputDir}")
 private String inputDir;

但有时候@Value(“${}”)取值为NULL,可能是由下面几个原因造成的:

1.类没有交给spring管理,即没有加上@Component等注解

@Service
public class TestValue{
    
    
    @Value("${inputDir}")
    private String inputDir;
    ……
    }

2.使用 static或final修饰成员变量

扫描二维码关注公众号,回复: 15093867 查看本文章
@Value("${inputDir}")
private static String inputDir;//错误,不能使用@Value给static成员变量赋值
@Value("${inputDir}")
private final String inputDir;//错误,不能使用@Value给final成员变量赋值

3.自己new了一个对象实例,而没有使用@Autowired注解

class Test{
    
    
    @AutoWired
    TestValue testValue
    //TestValue testValue = new TestValue()//错误,自己new的对象不能通过@Value注解获取配置值。
}

二.@Value{“#{}”}的使用

@RestController
@RequestMapping("/login")
@Component
public class LoginController {
    
    
	
	@Value("#{1}")
	private int number; //获取数字 1
	
	@Value("#{'Spring Expression Language'}") //获取字符串常量
	private String str;
	
	@Value("#{dataSource.url}") //获取bean的属性,dataSource为spring管理的obj,不是配置文件中的配置项
	private String jdbcUrl;
	
	@Autowired
	private DataSourceTransactionManager transactionManager;
 
	@RequestMapping("login")
	public String login(String name,String password) throws FileNotFoundException{
    
    
		System.out.println(number);
		System.out.println(str);
		System.out.println(jdbcUrl);
		return "login";
	}
}

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43842093/article/details/130550063