黑马SpringBoot3:SpringBoot属性注入方式

黑马SpringBoot3:SpringBoot属性注入方式_第1张图片

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {

    private String url;
    private String driverClassName;
    private String username;
    private String password;

    public String getUrl() {
        return url;
    }

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

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
@Configuration 
@EnableConfigurationProperties(JdbcProperties.class) 
public class JdbcConfig { 
@Bean
public DataSource dataSource(JdbcProperties jdbc)
    { 
            DruidDataSource dataSource = new DruidDataSource(); 
            dataSource.setUrl(jdbc.getUrl());
            dataSource.setDriverClassName(jdbc.getDriverClassName()); 
            dataSource.setUsername(jdbc.getUsername()); 
            dataSource.setPassword(jdbc.getPassword()); 
            return dataSource; 
      } 
 } 
其它方式

黑马SpringBoot3:SpringBoot属性注入方式_第2张图片

使用更优雅的方式去配置

使用@ConfigurationProperties在方法上面使用

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

你可能感兴趣的:(黑马SpringBoot3:SpringBoot属性注入方式)