黑马SpringBoot3:SpringBoot属性注入方式


@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; 
      } 
 } 
其它方式

使用更优雅的方式去配置

使用@ConfigurationProperties在方法上面使用

@Configuration 
public class JdbcConfig { 
      @Bean // 声明要注入的属性前缀,Spring Boot会自动把相关属性通过set方法注入到DataSource中 
      @ConfigurationProperties(prefix = "jdbc") 
      public DataSource dataSource() 
       { 
            return new DruidDataSource(); 
       } 
} 
posted @ 2020-07-09 19:05  xidianzxm  阅读(254)  评论(0编辑  收藏  举报