springboot属性动态配置

配置文件存放位置

springboot默认会读取这个名字的文件,推荐命名(application.properties)
application.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.28.217:3306/yimocha?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=root

在这里插入图片描述

springboot属性动态方式一:

动态的配置类

package top.yimocha.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @Author yimocha
 * @Version 1.0
 * springBoot 属性动态方式一
 * 公有属性动态
 **/
@ConfigurationProperties(prefix = "jdbc")
@Data
public class JdbcConfigProperties {
    private String url;
    private String driverClassName;
    private String username;
    private String password;
}

使用类

package top.yimocha.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * @Author yimocha
 * @Version 1.0
 * 
 **/
@Configuration
@EnableConfigurationProperties(JdbcConfigProperties.class)
public class JdbcConfig {

   @Bean
   public DataSource dataSource(JdbcConfigProperties properties) {
       DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setPassword(properties.getPassword());
       	druidDataSource.setUsername(properties.getUsername());
        druidDataSource.setUrl(properties.getUrl());
        druidDataSource.setDriverClassName(properties.getDriverClassName());
        return druidDataSource;
    }

}

这种方式适合配置全局属性动态,需要在整个应用使用

springboot属性动态方式二:

使用类

package top.yimocha.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * @Author yimocha
 * @Date 2019/10/28 18:29
 * @Version 1.0
 * 属性动态java 的属性动态方式
 **/
@Configuration
public class JdbcConfig {

    @ConfigurationProperties(prefix = "jdbc")
    @Bean
    public DataSource dataSource() {
        return new DruidDataSource();
    }
}

只在本类使用,不涉及整个程序的互用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值