SpringBoot-属性直接注入

SpringBoot-属性直接注入

SpringBoot-属性直接注入

上面我们说到,如果公共的属性,我们可以使用Java类加载Properties文件,来达到复用的目的,在SpringBoot中,我们提供了更为简单的方法,即直接使用配置文件注入。

使用直接注入我们有以下的几个注意点:

  1. Properties文件中的key(如果有前缀则是前缀后的值 )必须和属性名一致

  2. 在需要使用到Properties属性文件中属性的方法上加上@ConfigurationProperties(“prefix=xxx”)

  3. 一定要提供要注入类的getter、setter方法

packagecn.rayfoo.config;

importcom.alibaba.druid.pool.DruidDataSource;
importlombok.Data;
importlombok.ToString;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.boot.context.properties.EnableConfigurationProperties;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.PropertySource;

importjavax.sql.DataSource;

/**
* @author 张瑞丰
* @description
* @date 2019/11/4
*/
@Configuration
publicclassJDBCConfig{

   @ConfigurationProperties(prefix="jdbc")
   publicDataSourcedataSource(JDBCPropertiesjdbcProperties){
       DruidDataSourcedruidDataSource=newDruidDataSource();
       //这里会自动setter属性
       returndruidDataSource;
  }
}
posted @ 2019-11-06 14:41  张瑞丰  阅读(827)  评论(0编辑  收藏  举报