java枚举如何使用spring的@value注入属性

 更新时间:2023年09月21日 10:29:14   作者:Mint6  
这篇文章主要介绍了java枚举如何使用spring的@value注入属性问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

java枚举使用spring的@value注入属性

背景

在spring中使用@value注解来达到动态配置线上和预发环境的参数,在普通类中可以随意使用@value实现,java枚举enum无法注入,

怎么解决这个问题?

public enum SpringValueEnum {
    TEACHER(0, "我是老师"),
    STUDENT(1, "我是学生") {
        @Override
        public String getDesc() {
            return PeopleEnumContainer.name;
        }
    };
    private Integer code;
    private String desc;
    SpringValueEnum(Integer code, String desc) {
        this.code = code;
        this.desc = desc;
    }
    public Integer getCode() {
        return code;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    @Component
    static class PeopleEnumContainer {
        private static String name;
        @Value("${people.student.desc}")
        public void init(String name) {
            PeopleEnumContainer.name = name;
        }
    }
}

如上,使用内部类注入,重写枚举属性get方法来达到动态替换的目的。

Spring @Value属性注入使用总结

@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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • MyBatis中的JdbcType映射使用详解

    MyBatis中的JdbcType映射使用详解

    这篇文章主要介绍了MyBatis中的JdbcType映射使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-11-11
  • java解析xml汇总_动力节点Java学院整理

    java解析xml汇总_动力节点Java学院整理

    这篇文章主要介绍了java解析xml汇总_动力节点Java学院整理的相关资料,需要的朋友可以参考下
    2017-07-07
  • Java设计模式--适配器模式详解

    Java设计模式--适配器模式详解

    这篇文章主要介绍了java设计模式之适配器模式Adapter的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-09-09
  • java设计优化之单例模式

    java设计优化之单例模式

    这篇文章主要为大家详细介绍了java设计优化中的单例模式,深入学习java单例模式,感兴趣的朋友可以参考一下
    2016-03-03
  • 详解mall整合SpringBoot+MyBatis搭建基本骨架

    详解mall整合SpringBoot+MyBatis搭建基本骨架

    这篇文章主要介绍了详解mall整合SpringBoot+MyBatis搭建基本骨架,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • 一文带你深入了解Java中延时任务的实现

    一文带你深入了解Java中延时任务的实现

    延时任务相信大家都不陌生,在现实的业务中应用场景可以说是比比皆是。这篇文章主要为大家介绍几种实现延时任务的办法,感兴趣的可以了解一下
    2022-11-11
  • Mybatis中 mapper-locations和@MapperScan的作用

    Mybatis中 mapper-locations和@MapperScan的作用

    这篇文章主要介绍了Mybatis中 mapper-locations和@MapperScan的作用,mybatis.mapper-locations在SpringBoot配置文件中使用,作用是扫描Mapper接口对应的XML文件,需要的朋友可以参考下
    2023-05-05
  • 深入理解mybatis的ParamNameResolver

    深入理解mybatis的ParamNameResolver

    ParamNameResolver是 MyBatis 中的一个重要组件,它为 MyBatis 提供了一种方便的方式来获取方法参数的名称,本文主要介绍了深入理解mybatis的ParamNameResolver,具有一定的参考价值,感兴趣的可以了解一下
    2023-08-08
  • 关于mybatis3中几个@Provider的使用方式

    关于mybatis3中几个@Provider的使用方式

    这篇文章主要介绍了关于mybatis3中几个@Provider的使用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • Windows使用多个JDK的方法详解

    Windows使用多个JDK的方法详解

    本文介绍了如何在Windows系统中同时使用多个JDK版本(JDK8和JDK21),并详细描述了修改环境变量和Path变量的步骤,以实现JDK版本的切换
    2024-12-12

最新评论