@Value注解对于我们做基于SpringBoot框架开发的人来说太熟悉不过了,哪个项目能离开它。
我们经常使用@Value注解获取配置文件中的变量,但是它的作用不止如此,让我们一起看下。
@Value 注解是 Spring 3.0 框架中用于从属性文件、环境变量或其他配置源中注入数值到 Spring 管理的 Bean 中的注解。它可以用于将外部配置的值注入到 Spring 管理的 Bean 的字段、构造函数参数、方法参数等位置。
@Value源码:
package org.springframework.beans.factory.annotation;
import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Value { String value();}
根据源码中的@Target,@Value可以用在字段、方法、构造函数参数和注解类型中。
下面是 @Value 注解的一些常见用法:
注入基本类型值
@Value("100")private int intValue;
注入字符串类型值
@Value("Hello, World!")private String message;
注入属性文件中的值
@Value("${app.name}")private String appName;
注入环境变量中的值
@Value("${JAVA_HOME}")private String javaHome;
SpEL表达式
@Value("#{systemProperties['user.language']}")private String userLanguage;
构造函数参数注入
public MyClass(@Value("${app.version}") String version) { // ...}
请求参数的默认值
@RequestMapping("/hello")public String hello(@RequestParam(defaultValue="${app.greeting}") String greeting) { return greeting;}
让我们通过一个示例代码运行一下@Value的用法。
import javax.annotation.PostConstruct;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Configuration;
/** * @Value的用法演示 * @author * @date * @Description * */@SpringBootApplicationpublic class SpringApp { public static void main(String[] args) { SpringApplication.run(SpringApp.class, args); } }
@Configurationclass AppConfig { @Value("100") private int intValue;
@Value("Hello, World!") private String message;
@Value("${app.name}") private String appName;
@Value("${JAVA_HOME}") private String javaHome;
@Value("#{systemProperties['user.language']}") private String userLanguage;
public AppConfig(@Value("${spring.tel}") String tel) { System.out.println(tel); } @PostConstruct public void init() { System.out.println(intValue); System.out.println(message); System.out.println(appName); System.out.println(javaHome); System.out.println(userLanguage); }}
运行结果:
以上就是 @Value 注解的大部分用法,当然可能不限于此。
你还知道它有哪些用法呢?
领取专属 10元无门槛券
私享最新 技术干货