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