springboot的配置文件参数读取和4种属性注入

springboot的配置文件参数读取

springboot项目启动时会自动读取项目下application.properties中的配置。
当以需要读取application.properties中的参数时,可以使用@ConfigurationProperties注解读取,然后在要使用到的类种用@EnableConfigurationProperties((JdbcProperties.class))启用。

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;

    //getter、setter方法省略
}
@Configuration//声明一个类是java配置类,相当于一个配置文件
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

    @Autowired
    private JdbcProperties jdbcProperties;

    @Bean
    public DataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(this.jdbcProperties.getDriverClassName());
        druidDataSource.setUrl(this.jdbcProperties.getUrl());
        druidDataSource.setUsername(this.jdbcProperties.getUsername());
        druidDataSource.setPassword(this.jdbcProperties.getPassword());
        return druidDataSource;
    }
}

springboot的4种属性注入方式

1.@Autowired(最常用)
通过setter方法注入
在这里插入图片描述
2.构造方法注入
在这里插入图片描述
3.@Bean形参注入
在这里插入图片描述
4.在@Bean方法上使用@ConfigurationProperties(prefix=“jdbc”)
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值