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

本文介绍SpringBoot中如何引入properties配置文件及注入到bean的方法,包括@PropertySource和@Value的使用,以及@PropertySource和@ConfigurationProperties的组合使用。

本篇,我们介绍下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

 

 

 

在 Spring Boot 项目中使用 Forest 框架调用第三方 API,可以通过声明式接口的方式简化 HTTP 请求的编写和管理。以下是详细的实现方法: ### 1. 添加 Forest 依赖 首先,在 `pom.xml` 文件中添加 Forest 的 Spring Boot Starter 依赖。该依赖会自动引入 Forest 核心库以及与 Spring Boot 的集成支持[^2]。 ```xml <dependency> <groupId>com.dtflys.forest</groupId> <artifactId>spring-boot-starter-forest</artifactId> <version>1.5.0-BETA5</version> </dependency> ``` 如果使用的是较新的 Spring Boot 版本,建议查看官方文档以确认兼容的 Forest 版本。 ### 2. 定义接口调用第三方 API 接下来,定义一个接口来声明要调用的第三方 API。使用 Forest 提供的注解(如 `@Get`、`@Post`)来指定请求方法和 URL。例如: ```java import com.dtflys.forest.annotation.Get; public interface IUserClient { @Get(url = "http://localhost:8080/forest-server/userService/getUserPasswordByName?userName=${0}") String getUserPasswordByName(String userName); } ``` 该接口定义了一个 `GET` 请求,调用本地服务的 `/forest-server/userService/getUserPasswordByName` 接口并传入用户名参数。 ### 3. 启用 Forest 扫描 在 Spring Boot 启动类上添加 `@ForestScan` 注解,指定包含 Forest 客户端接口的包路径。这样 Spring Boot 会在启动时自动扫描并注册这些接口为 Bean[^3]。 ```java import com.dtflys.forest.springboot.annotation.ForestScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @ForestScan(basePackages = "cn.olive.forest.client") public class ForestClientApplication { public static void main(String[] args) { SpringApplication.run(ForestClientApplication.class, args); } } ``` ### 4. 在服务中注入并使用接口 在业务服务中,可以直接注入定义的 Forest 接口并调用其方法。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { private final IUserClient userClient; @Autowired public UserService(IUserClient userClient) { this.userClient = userClient; } public String fetchUserPassword(String username) { return userClient.getUserPasswordByName(username); } } ``` ### 5. 配置 Forest(可选) Forest 提供了丰富的配置选项,如设置超时时间、重试策略、日志级别等。可以在 `application.yml` 或 `application.properties` 中进行全局或接口级别的配置[^1]。 ```yaml forest: config: timeout: 3000 retry-count: 3 log-enabled: true ``` 此外,也可以通过接口方法上的注解实现更细粒度的配置。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值