服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 使用springboot配置和占位符获取配置文件中的值

使用springboot配置和占位符获取配置文件中的值

2022-08-01 12:08托尼吴 Java教程

这篇文章主要介绍了使用springboot配置和占位符获取配置文件中的值,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

springboot配置和占位符获取配置文件值

@PropertySource& 加载指定的配置文件

package com.example.springbootdemo.pojo; 
import com.alibaba.fastjson.JSON;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
 
/**
 * ***GOOD LUCK****
 *
 * @Author : Wukn
 * @Date : 2018/6/
 *
 * 将配置文件中的的每一个属性的值,映射到这个组建中
 *@ConfigurationProperties
 * prefix = "persion"   指定在配置文件中需要将persion的配置属性映射到这个实体类中
 */
 
/**
 * 获取指定配置文件
 * @PropertySource( value = {"classpath:coms.properties"})
 */
 
@Component
/**
 * @ConfigurationProperties(prefix = "persion"),默认获取根目录下的值
 */
@ConfigurationProperties(prefix = "persion")
public class Persion {  
    private String name;
    private Integer id;
    private Boolean bool;  
    public Persion() {
    }  
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public Boolean getBool() {
        return bool;
    }
 
    public void setBool(Boolean bool) {
        this.bool = bool;
    }
 
    @Override
    public String toString() {
        return JSON.toJSONString( this );
    }
}

使用springboot配置和占位符获取配置文件中的值

@ImportResource 导入指定的配置文件

使用springboot配置和占位符获取配置文件中的值

以上方式过于麻烦,springboot推荐通过全注解方式,添加组件的方式

通过注解@Configration申明一个配置类,通过注解@Bean可以使用在方法上面,申明一个组件的生成,要是放在方法上,表明这个方法的返回值放在ioc容器中

package com.example.springbootdemo.configration;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
/**
 * Created with IntelliJ IDEA.
 * Description: Cms数据源的一些设置
 * Date: 2018-06-08
 * Time: 5:50 PM
 *
 * @author: wukn
 */
@Configuration
public class DataConfig { 
 
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility( PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    } 
}

通过占位符获取值

 
#通过使用占位符赋值
persion.name=张三${random.value}
persion.bool=false
persion.id=12${random.int}
 
person.last‐name=张三${random.uuid}
person.age=${random.int} 
person.birth=2017/12/15 person.boss=false 
person.maps.k1=v1 person.maps.k2=14 person.lists=a,b,c 
person.dog.name=${person.hello:hello}_dog 
person.dog.age=15

springboot配置文件,占位符的使用

首先要给到注解

让user类可用通过配置文件进行实例化

使用springboot配置和占位符获取配置文件中的值

package com.example.springdemo.entity;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated; 
import java.util.List;
 
@Component//把User加到容器中
@Data
/**
 * @ConfigurationProperties
 * 可以将配置文件中的每一个属性的值,映射到这个组件中
 * 告诉springboot将奔雷中的所有属性和配置文件中的相关属性先绑定
 * prefix = "com"绑定配置文件com层级下的属性进行一一映射
 * 只有是容器才能使用所以要添加注解@Component
 */
@ConfigurationProperties(prefix = "com")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private List<Object>list;
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Integer getAge(int i) {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    private String email;
 
    public Integer getAge() {
        return age;
    }
 
    public List<Object> getList() {
        return list;
    }
 
    public void setList(List<Object> list) {
        this.list = list;
    }
}

配置文件

com.email=99@dfp.com
com.name=newDFP${com.cc:不存在给默认值}
com.age=${random.int}

首先就是对age取随机数然后对name获取对象的数据

运行最后一个测试类

package com.example.springdemo; 
import com.example.springdemo.entity.User;
import com.example.springdemo.mapper.UserMapper;
import com.example.springdemo.properties.Myproperties;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
 
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;
 
@SpringBootTest
@RunWith(SpringRunner.class)
class SpringdemoApplicationTests {
 
//如果测试类与启动入口类包名不一致,必须加该注解属性classes指定启动入口类,否则无法启动SpringBoot
        @Autowired
        private DataSource dataSource;
 
        @Test
        public void dataSource() {
            try {
                System.out.println(dataSource.getConnection());
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    @Autowired
    Myproperties myproperties;
    @Test
    void test(){
        System.out.println("------------------------");
        System.out.println(myproperties.getMes());
    }
 
    @Autowired
    UserMapper userMapper;
    @Test
    void testMybatisPlus(){
        List<User> users=userMapper.selectList(null);
        for (User user:users){
            System.out.println(user);
        }
        System.out.println("查询成功!");
        User aduuser=new User();
//        aduuser.setName("DFP");
//        aduuser.setAge(18);
//        aduuser.setEmail("DFP19053025@qq.com");
//        aduuser.setId(19053065L);
        int i=userMapper.insert(aduuser);
        if (i>0){
            System.out.println("成功加入记录!");
        }else{ System.out.println("失败加入记录!");}
        for (User user:users){
            System.out.println(user);
        } 
    }
 
    @Autowired
    User user;
    @Test
    public void contextlodes(){
        System.out.println("测试结果输出:"+user);
    }
}

结果

使用springboot配置和占位符获取配置文件中的值

因为com.cc是不存在的就回去:后面的默认值

如果com.cc存在就会取com.cc的值

测试如下

com.email=99@dfp.com
com.name=newDFP+++${com.email:不存在给默认值}
com.age=${random.int}

这次的值不再是默认值了com.email是存在数据的

使用springboot配置和占位符获取配置文件中的值

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

原文地址:https://wukainian.blog.csdn.net/article/details/82425264

延伸 · 阅读

精彩推荐
  • Java教程Spring中@Transactional用法详细介绍

    Spring中@Transactional用法详细介绍

    这篇文章主要介绍了Spring中@Transactional用法详细介绍的相关资料,需要的朋友可以参考下...

    bladestone3662020-08-06
  • Java教程Java Web制作登录验证码实现代码解析

    Java Web制作登录验证码实现代码解析

    这篇文章主要介绍了Java Web制作登录验证码实现代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可...

    勤快的懒羊羊2542020-09-26
  • Java教程Java DatabaseMetaData用法案例详解

    Java DatabaseMetaData用法案例详解

    这篇文章主要介绍了Java DatabaseMetaData用法案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下...

    liuleigang7532021-12-07
  • Java教程详解Springboot事务管理

    详解Springboot事务管理

    本篇文章主要介绍了详解Springboot事务管理,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    icecrea6472021-03-09
  • Java教程JWT在OpenFeign调用中进行令牌中继详解

    JWT在OpenFeign调用中进行令牌中继详解

    Feign是一个声明式的Web Service客户端,是一种声明式、模板化的HTTP客户端。而OpenFeign是Spring Cloud 在Feign的基础上支持了Spring MVC的注解,如@RequesMapping等等,这...

    码农小胖哥6412022-03-02
  • Java教程实例讲述Java IO文件复制

    实例讲述Java IO文件复制

    本篇文章通过实例给大家详细讲述Java IO文件复制的相关知识点,需要的读者们学习下吧。 ...

    idaobin9802021-04-08
  • Java教程Java中Switch用法代码示例

    Java中Switch用法代码示例

    这篇文章主要介绍了Java中Switch用法代码示例,向大家分享了两段代码,具有一定参考价值,需要的朋友可以了解下。...

    Java_Swing10932021-01-29
  • Java教程修改IDEA代码左侧折叠线颜色的操作

    修改IDEA代码左侧折叠线颜色的操作

    这篇文章主要介绍了修改IDEA代码左侧折叠线颜色的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    FocusAgain4022021-08-06