Spring Boot系列四 Spring @Value 属性注入使用总结一

25 篇文章 37 订阅
8 篇文章 2 订阅

@Value注入

不通过配置文件的注入属性的情况

通过@Value将外部的值动态注入到Bean中,使用的情况有:

  • 注入普通字符串
  • 注入操作系统属性
  • 注入表达式结果
  • 注入其他Bean属性:注入beanInject对象的属性another
  • 注入文件资源
  • 注入URL资源

    详细代码见:

    @Value("normal")
    private String normal; // 注入普通字符串

    @Value("#{systemProperties['os.name']}")
    private String systemPropertiesName; // 注入操作系统属性

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber; //注入表达式结果

    @Value("#{beanInject.another}")
    private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面

    @Value("classpath:com/hry/spring/configinject/config.txt")
    private Resource resourceFile; // 注入文件资源

    @Value("http://www.baidu.com")
    private Resource testUrl; // 注入URL资源

注入其他Bean属性:注入beanInject对象的属性another

@Component
public class BeanInject {
    @Value("其他Bean的属性")
    private String another;

    public String getAnother() {
        return another;
    }

    public void setAnother(String another) {
        this.another = another;
    }
}

注入文件资源:com/hry/spring/configinject/config.txt

test configuration file

测试类:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class ConfiginjectApplicationTest {
    @Autowired
    private BaseValueInject baseValueInject;

    @Test
    public void baseValueInject(){
        System.out.println(baseValueInject.toString());
    }
}

运行测试类

normal=normal
systemPropertiesName=Windows 10
randomNumber=35.10603794922444
fromAnotherBean=其他Bean的属性
resourceFile=test configuration file
testUrl=<html>...<title>百度一下,你就知道</title>...略</html>

通过配置文件的注入属性的情况

通过@Value将外部配置文件的值动态注入到Bean中。配置文件主要有两类:

  • application.properties。application.properties在spring boot启动时默认加载此文件
  • 自定义属性文件。自定义属性文件通过@PropertySource加载。@PropertySource可以同时加载多个文件,也可以加载单个文件。如果相同第一个属性文件和第二属性文件存在相同key,则最后一个属性文件里的key启作用。加载文件的路径也可以配置变量,如下文的${anotherfile.configinject},此值定义在第一个属性文件config.properties

第一个属性文件config.properties内容如下:
${anotherfile.configinject}作为第二个属性文件加载路径的变量值

book.name=bookName
anotherfile.configinject=placeholder

第二个属性文件config_placeholder.properties内容如下:

book.name.placeholder=bookNamePlaceholder

下面通过@Value(“${app.name}”)语法将属性文件的值注入bean属性值,详细代码见:

@Component
// 引入外部配置文件组:${app.configinject}的值来自config.properties。
// 如果相同
@PropertySource({"classpath:com/hry/spring/configinject/config.properties",
    "classpath:com/hry/spring/configinject/config_${anotherfile.configinject}.properties"})
public class ConfigurationFileInject{
    @Value("${app.name}")
    private String appName; // 这里的值来自application.properties,spring boot启动时默认加载此文件

    @Value("${book.name}")
    private String bookName; // 注入第一个配置外部文件属性

    @Value("${book.name.placeholder}")
    private String bookNamePlaceholder; // 注入第二个配置外部文件属性

    @Autowired
    private Environment env;  // 注入环境变量对象,存储注入的属性值

    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("bookName=").append(bookName).append("\r\n")
        .append("bookNamePlaceholder=").append(bookNamePlaceholder).append("\r\n")
        .append("appName=").append(appName).append("\r\n")
        .append("env=").append(env).append("\r\n")
        // 从eniroment中获取属性值
        .append("env=").append(env.getProperty("book.name.placeholder")).append("\r\n");
        return sb.toString();
    }   
}

测试代码:
Application.java同上文


@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class ConfiginjectApplicationTest {
    @Autowired
    private ConfigurationFileInject configurationFileInject;

    @Test
    public void configurationFileInject(){
        System.out.println(configurationFileInject.toString());
    }
}

测试运行结果:

bookName=bookName
bookNamePlaceholder=bookNamePlaceholder
appName=appName
env=StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[Inlined Test Properties,systemProperties,systemEnvironment,random,applicationConfig: [classpath:/application.properties],class path resource [com/hry/spring/configinject/config_placeholder.properties],class path resource [com/hry/spring/configinject/config.properties]]}
env=bookNamePlaceholder

代码

Github代码

  • 12
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot中,可以使用`@Value`注解来注入配置文件中的属性值。对于复杂类型的属性值,可以使用`SpEL`表达式来实现注入。 例如,假设我们有一个配置文件`application.properties`,其中定义了一个复杂类型的属性值: ``` my.complex.property={ "name": "John", "age": 30 } ``` 可以在Spring Boot的组件中使用`@Value`注解来注入属性值: ```java @Component public class MyComponent { @Value("#{${my.complex.property}}") private Map<String, Object> myComplexProperty; // ... } ``` 在上面的代码中,`MyComponent`组件使用`@Value`注解注入了`my.complex.property`属性值,并使用`SpEL`表达式将该属性值转换为一个`Map`对象。`SpEL`表达式`#{${my.complex.property}}`表示`${my.complex.property}`是一个字符串类型的属性值,需要使用`#{}`包装起来,并在内部使用两个大括号`{}`表示将该字符串解析为一个Map对象。同时,由于`my.complex.property`属性值是一个字符串类型,所以在`@Value`注解中需要使用双引号`""`将其包装起来。 需要注意的是,`SpEL`表达式中的双引号`""`和单引号`''`有不同的含义。双引号表示表达式中的字符串,而单引号表示表达式中的字符。如果属性值中包含了双引号或者单引号,可以使用转义符`\`将其转义。 另外,对于复杂类型的属性值,也可以使用`@ConfigurationProperties`注解来注入,具体可参考官方文档:[https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties](https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config.typesafe-configuration-properties)。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值