SpringBoot 的四种属性注入方式

1.Autowired注入方式(以注入连接池为例)

application.properties 配置文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/springboot
jdbc.username=root
jdbc.password=root

1. 创建一个属性读取类:JdbcProperties

/**
 * 属性读取类
 *  prefix: 为application.properties文件中的前缀 
 */
@ConfigurationProperties(prefix = "jdbc")  //读取配置文件,声明一个类是读取配置类
public class JdbcProperties {
    private String driverClassName;  //配置文件中的属性名称
    private String url;
    private String username;
    private String password;
   
    //get、set方法
}
  • 在类上通过@ConfigurationProperties注解声明当前类为属性读取类

  • prefix="jdbc"读取属性文件中,前缀为jdbc的值。

  • 在类上定义各个属性,名称必须与属性文件中 jdbc. 后面部分一致,并且必须具有 getter 和 setter 方法

  • SpringBoot默认会读取文件名为 application.properties 的资源文件,所以配置文件名必须为 application.properties

2. 创建另一个类 JdbcConfiguration 使用这个属性

  • 通过@EnableConfigurationProperties(JdbcProperties.class)来声明要使用JdbcProperties这个类的对象

  • 然后你可以通过以下方式在 JdbcConfiguration 类中注入 JdbcProperties:

@Configuration //声明一个类为Java配置类,相当于一个xml文件
@EnableConfigurationProperties(JdbcProperties.class)  //启用属性读取类
public class JdbcConfiguration {
    @Autowired
    private JdbcProperties jdbcProperties;  //注入读取类

    @Bean        //把方法返回值注入到spring容器
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.jdbcProperties.getDriverClassName());
        dataSource.setUrl(this.jdbcProperties.getUrl());
        dataSource.setUsername(this.jdbcProperties.getUsername());
        dataSource.setPassword(this.jdbcProperties.getPassword());
        return dataSource;
    }
}

2. 构造函数注入

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

    private JdbcProperties jdbcProperties;

    public JdbcConfiguration(JdbcProperties jdbcProperties){
        this.jdbcProperties = jdbcProperties;
    }

    @Bean
    public DataSource dataSource() {
        // 略
    }

}

3. @Bean方法的参数注入

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfiguration {

    @Bean
    public DataSource dataSource(JdbcProperties jdbcProperties) {
        // ...
    }
}

4. 把 @ConfigurationProperties(prefix = "jdbc") 声明在需要使用的 @Bean 的方法上

然后 SpringBoot 就会自动调用这个 Bean(此处是DataSource)的 set 方法,然后完成注入。使用的前提是:该类必须有对应属性的 set 方法.

@Configuration
public class JdbcConfiguration {
    
    @Bean
    // 声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DataSource中
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }
}

参考资源

  1. https://www.jianshu.com/p/add1faa168b4

  2. https://www.cnblogs.com/cqyp/p/13229957.html

每天学习一点点,每天进步一点点。

posted @ 2021-07-30 09:56  爱吃西瓜的番茄酱  阅读(1534)  评论(0编辑  收藏  举报