配置文件存放位置
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();
}
}
只在本類使用,不涉及整個程序的互用