三、读取外部的资源配置文件并配置数据库连接池

1、读取外部的资源配置文件

通过@PropertySource可以指定读取的配置文件,通过@Value注解获取值,具体用法:

@Configuration //通过该注解来表明该类是一个Spring的配置,相当于一个xml文件
@ComponentScan(basePackages = "cn.mmzs.springboot") //配置扫描包
@PropertySource(value= {"classpath:jdbc.properties"})
public class SpringConfig {
    
    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Bean // 通过该注解来表明是一个Bean对象,相当于xml中的<bean>
    public UserDao getUserDAO(){
        return new UserDao(); // 直接new对象做演示
    }
    
}

思考:

1)、  如何配置多个配置文件?

//获取多个资源文件
@PropertySource(value= {"classpath:jdbc.properties","classpath:log4j.properties","xxx"})

2)、如果配置的配置文件不存在会怎么样?

//使用,ignoreResourceNotFound设置为true来进行忽略没有找到的配置文件
@PropertySource(value= {"classpath:jdbc.properties"},ignoreResourceNotFound = true)//获取一个资源文件
@PropertySource(value= {"classpath:jdbc.properties","classpath:log4j.properties","xxx"},ignoreResourceNotFound = true)//获取多个资源文件

2、配置数据库连接池

a、导入依赖

<!-- 连接池 -->
<dependency>
    <groupId>com.jolbox</groupId>
    <artifactId>bonecp-spring</artifactId>
    <version>0.8.0.RELEASE</version>
</dependency>

b、利用xml文件配置时:

 1 jdbc.driverClassName=com.mysql.jdbc.Driver
 2 #数据库的路径
 3 #url=jdbc:mysql://localhost:3306/springboot
 4 jdbc.url=jdbc:mysql://localhost:3306/house
 5 jdbc.username=root
 6 jdbc.password=123456
 7 #定义初始连接数
 8 initialSize=0
 9 #定义最大连接数
10 maxActive=20
11 #定义最大空闲
12 maxIdle=20
13 #定义最小空闲
14 minIdle=1
15 #定义最长等待时间
16 maxWait=60000
jdbc.properties

相关文章:

  • 2021-11-11
  • 2022-02-09
  • 2022-02-08
  • 2021-07-08
  • 2021-04-04
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-31
  • 2022-12-23
  • 2021-08-30
  • 2022-12-23
  • 2021-07-24
  • 2021-08-04
相关资源
相似解决方案