Spring Boot06

先记住一个单词,后面会用到Conditional:有条件的,条件的

目录

3.5使用属性文件

使用默认配置文件

使用自定义配置文件

3.6条件装配Bean


3.5使用属性文件

使用默认配置文件

对于属性文件,在项目中十分常见,比如连接数据库的jdbc.properties,日志文件的配置等,那在Spring Boot我们如何使用嘞!今天就来聊一聊

在SpringBoot中,我们可以使用默认的application.properties配置文件 ,也可以使用自定义的配置文件

我们来举个例子

  1. 在Maven项目中添加SpringBoot配置上下文依赖,这样SpringBoot将创建读取配置文件的上下文
  2. 配置属性
  3. 使用配置的属性
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
database.driverName=com.mysql.jdbc.Driver
database.url=jdbc:mysql;//localhost:3306/user
database.username=root
database.password=root
@Component
public class Dataproperties {
    @Value("${database.driverName}")
    private String  driverName = null;
    @Value("${database.url}")
    private String  url = null;
    private String  username = null;
    private String  password = null;

    public void setDriverName(String driver) {
        System.out.println(driver);
        this.driverName = driver;
    }

    public void setUrl(String url) {
        System.out.println(url);
        this.url = url;
    }
    @Value("${database.username}")
    public void setUsername(String username) {
        System.out.println(username);
        this.username = username;
    }
    @Value("${database.password}")
    public void setPassword(String password) {
        System.out.println(password);
        this.password = password;
    }
}

 运行结果(启动项目)

 我们可以使用@Value注解,配合Spring表达式获取属性文件的内容,@Value注解既可以加在属性,也可以加在方法上

我们也可以使用注解@ConfigurationProperties获取配置属性,效果是一样的

@ConfigurationProperties中配置的database,将与POJO的属性名称组成属性的全限定名去配置文件里查找

@Component
@ConfigurationProperties("database")
public class Dataproperties {

    private String  driverName = null;
    private String  url = null;
    private String  username = null;
    private String  password = null;

    public void setDriverName(String driver) {
        System.out.println(driver);
        this.driverName = driver;
    }

    public void setUrl(String url) {
        System.out.println(url);
        this.url = url;
    }

    public void setUsername(String username) {
        System.out.println(username);
        this.username = username;
    }

    public void setPassword(String password) {
        System.out.println(password);
        this.password = password;
    }
}

使用自定义配置文件

如果我们将所有的配置都放在默认的配置文件中,不仅容易搞混,也不利于维护,因此我们来学习自定义配置文件,我们要介绍一个注解——@PropertySource用于加载我们自定义的配置文件

在启动类中加上如下注解,value可以指定多个配置文件,ignoreResourceNotFound=true表示如果没有找到配置文件,也不会报错

@PropertySource(value = {"classpath:jdbc.properties"},ignoreResourceNotFound = true)

再来创建一个jdbc.properties文件

database.driverName=com.mysql.jdbc.Driver
database.url=jdbc:mysql;//localhost:3306/user
database.username=root
database.password=root

测试结果

3.6条件装配Bean

可能因为某些原因,Bena无法进行初始化,比如数据库连接池的配置中漏掉了一些配置导致数据源连接不上,这个时候IoC容器如果进行数据源的装配,将会报错,导致应用无法继续,这并不是我们所希望的,我们不可能因为一个功能的失效导致整个项目停止服务,这个时候我们还是希望IoC容器不去装配数据源

为了处理这样的情景,Spring提供了@Conditional注解帮助我们,而它需要配合另外一个接口Conditional来完成对应的功能

我们来演示一下

首先导入对应坐标

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-dbcp2</artifactId>
</dependency>

 创建配置类Config用于配置装配DBCP数据源

@Configuration
public class Conifg {
    @Bean(name = "dataSource",destroyMethod = "close")
    @Conditional(DatabaseConditional.class)
    public DataSource getSource(
            @Value("${database.driverName}") String driverName,
            @Value("${database.url}") String url,
            @Value("${database.username}") String username,
            @Value("${database.password}") String password){




        Properties properties = new Properties();
        properties.setProperty("driverName",driverName);
        properties.setProperty("url",url);
        properties.setProperty("username",username);
        properties.setProperty("password",password);


        DataSource dataSource = null;
        try {
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;

    }
}

可以看到我们加入了@Conditional注解,并且指定了类,我们下面来编写对于的类

创建DatabaseConditional类,并且要实现Condition接口实现matches方法

public class DatabaseConditional implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //取出环境配置
        Environment environment = context.getEnvironment();
        //判断属性文件是否存在对应的数据库的配置
        return environment.containsProperty("database.driverName")
                &&environment.containsProperty("database.url")
                &&environment.containsProperty("database.username")
                &&environment.containsProperty("database.password");
    }
}

matches方法首先读取其上下文环境,然后判断是否已经配置了对应的数据库信息,如果都配置好则返回true,spring会装配数据库连接池的Bean,否则是不装配的。

好了,今天的学习就到这里,各位晚安

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不背八股睡不着

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值