欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot(七)--引入properties配置文件注入bean

程序员文章站 2022-05-02 12:13:54
...

本篇,我们介绍下springboot中如何引入properties配置文件,以及如何将properties配置文件中键/值如何注入到spring的bean中。

笔者总结了下,使用较多的大概有两种方式:

一、使用@PropertySource和@Value

例如,配置jdbc连接池,需要使用到jdbc.properties配置文件 (druid数据库连接池)

DataSourceConfiguration.java

import javax.sql.DataSource;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
 
import com.alibaba.druid.pool.DruidDataSource;
 
@Configuration
@PropertySource(value = { "classpath:/jdbc.properties"})
public class DataSourceConfig {
 
       @Value("${jdbc.driverClassName}")
       private String driverClassName ;
        
       @Value("${jdbc.url}")
       private String   url ;
        
       @Value("${jdbc.username}")
       private String username ;
        
       @Value("${jdbc.password}")
       private String password ;
        
       @Value("${jdbc.initialSize}")
       private int  initialSize ;
          
      @Value("${jdbc.maxActive}")
      private int   maxActive ;
        
      @Value("${jdbc.minIdle}")
      private int   minIdle ;
       
      @Value("${jdbc.maxWait}")
      private long  maxWait ;
       
       @Value("${jdbc.removeAbandoned}")
      private boolean   removeAbandoned ;
       @Value("${jdbc.removeAbandonedTimeout}")
      private int   removeAbandonedTimeout ;
        
       @Value("${jdbc.timeBetweenEvictionRunsMillis}")
      private long timeBetweenEvictionRunsMillis ;
       @Value("${jdbc.minEvictableIdleTimeMillis}")
      private long minEvictableIdleTimeMillis ;
       @Value("${jdbc.validationQuery}") 
      private String validationQuery ;
       @Value("${jdbc.testWhileIdle}")
      private boolean testWhileIdle ;
       @Value("${jdbc.testOnBorrow}")
      private boolean testOnBorrow ;
       @Value("${jdbc.testOnReturn}")
      private boolean testOnReturn ;
       @Value("${jdbc.poolPreparedStatements}")
      private boolean poolPreparedStatements ;
        
       @Value("${jdbc.maxPoolPreparedStatementPerConnectionSize}")
      private int maxPoolPreparedStatementPerConnectionSize ;
      
 
          
 
        @Bean(initMethod="init",destroyMethod="close")
        public DataSource dataSource() {
            DruidDataSource  ds=new  DruidDataSource();
            ds.setDriverClassName(driverClassName);
            ds.setUrl(url);
            ds.setUsername(username);
            ds.setPassword(password);
            ds.setInitialSize(initialSize);
            ds.setMaxActive(maxActive);
            ds.setMinIdle(minIdle);
            ds.setMaxWait(maxWait);
            ds.setRemoveAbandoned(removeAbandoned);
            ds.setRemoveAbandonedTimeout(removeAbandonedTimeout);
             
            ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
            ds.setValidationQuery(validationQuery);
            ds.setTestWhileIdle(testWhileIdle);
            ds.setTestOnBorrow(testOnBorrow);
            ds.setTestOnReturn(testOnReturn);
             
            ds.setPoolPreparedStatements(poolPreparedStatements);
             
            ds.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
            return ds;
        }
     
}

jdbc.properties

#驱动全类名
jdbc.driverClassName = com.mysql.jdbc.Driver
#jdbc url
jdbc.url =jdbc:mysql://localhost:3306/sbdemo?useUnicode=true&characterEncoding=UTF8&useSSL=false
jdbc.username = root
jdbc.password = 123456
#初始化连接数
jdbc.initialSize = 3
#最大活跃连接数
jdbc.maxActive = 100
#最小空闲连接数
jdbc.minIdle = 2
#最大连接等待时间 毫秒
jdbc.maxWait = 60000
#超过时间限制是否回收
jdbc.removeAbandoned = true
#超时丢弃连接 1800秒    即30分钟
jdbc.removeAbandonedTimeout = 1800
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
jdbc.timeBetweenEvictionRunsMillis = 60000
#配置一个连接在池中最小生存的时间,单位是毫秒
jdbc.minEvictableIdleTimeMillis = 300000
#用来检测连接是否有效的sql,要求是一个查询语句	
jdbc.validationQuery = SELECT 1 FROM DUAL
#申请连接的时候检测
jdbc.testWhileIdle =true
#申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能
jdbc.testOnBorrow = false
#归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能 
jdbc.testOnReturn = false
#打开PSCache,并且指定每个连接上PSCache的大小
jdbc.poolPreparedStatements = true
jdbc.maxPoolPreparedStatementPerConnectionSize = 20
# 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:  监控统计stat   日志用的log4j 防御SQL注入的wall
#filters =stat,config
# 解密密码必须要配置的项 config, stat启用监控过滤器
# connectionProperties=config.decrypt\=true

二、使用@PropertySource和@ConfigurationProperties

  @ConfigurationProperties 可以一次性注入properties中指定前缀的所有字段(不指定前缀则注入所有字段),无须用@Value一个个字段的注入,例如项目中配置一个ftp连接池对象。

FTPConfigBean.java

@Component
@PropertySource("classpath:/ftp.properties")
@ConfigurationProperties(prefix="ftp")
public class FTPConfigBean {
     
    private String host ;
    private int port ;
    private String username;
    private String password;
    private int connectTimeOut;
    private String controlEncoding;
    private  int bufferSize;
    private int fileType;
    private  int dataTimeout;
    private boolean useEPSVwithIPv4;
    private  boolean  passiveMode;
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getConnectTimeOut() {
        return connectTimeOut;
    }
    public void setConnectTimeOut(int connectTimeOut) {
        this.connectTimeOut = connectTimeOut;
    }
    public String getControlEncoding() {
        return controlEncoding;
    }
    public void setControlEncoding(String controlEncoding) {
        this.controlEncoding = controlEncoding;
    }
    public int getBufferSize() {
        return bufferSize;
    }
    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }
    public int getFileType() {
        return fileType;
    }
    public void setFileType(int fileType) {
        this.fileType = fileType;
    }
    public int getDataTimeout() {
        return dataTimeout;
    }
    public void setDataTimeout(int dataTimeout) {
        this.dataTimeout = dataTimeout;
    }
    public boolean isUseEPSVwithIPv4() {
        return useEPSVwithIPv4;
    }
    public void setUseEPSVwithIPv4(boolean useEPSVwithIPv4) {
        this.useEPSVwithIPv4 = useEPSVwithIPv4;
    }
    public boolean isPassiveMode() {
        return passiveMode;
    }
    public void setPassiveMode(boolean passiveMode) {
        this.passiveMode = passiveMode;
    }
    @Override
    public String toString() {
        return "FTPConfigBean [host=" + host + ", port=" + port + ", username="
                + username + ", password=" + password + ", connectTimeOut="
                + connectTimeOut + ", controlEncoding=" + controlEncoding
                + ", bufferSize=" + bufferSize + ", fileType=" + fileType
                + ", dataTimeout=" + dataTimeout + ", useEPSVwithIPv4="
                + useEPSVwithIPv4 + ", passiveMode=" + passiveMode + "]";
    }
     
     
}

ftp.properties

ftp.host=192.168.9.130
ftp.port=21
ftp.username=myftp
ftp.password=123456


#ftp 连接超时时间 毫秒
ftp.connectTimeOut=5000
#控制连接  字符编码
ftp.controlEncoding=UTF-8
#缓冲区大小
ftp.bufferSize=1024
#传输文件类型   2表二进制
ftp.fileType=2
#数据传输超时 毫秒
ftp.dataTimeout=120000
#
ftp.useEPSVwithIPv4=false
#是否启用ftp被动模式
ftp.passiveMode=true