SpringBoot-Properties配置文件属性注入-1

SpringBoot-Properties配置文件属性注入-1

标签(空格分隔): java,SpringBoot

1.创建配置文件[application.properties]

springboot-配置文件.png

2.创建JdbcProperties类

package com.itheima.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;


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

    private String driverClassName;

    private String url;

    private String username;

    private String password;
}

3.创建JdbcConfig类

package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig1 {
    
    
    // 也可以构造注入
    @Autowired
    private JdbcProperties jdbcProperties;


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

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

4.Debug运行测试

springboot-注入测试.png

posted @ 2020-07-25 16:46  TaylorSWMM  阅读(990)  评论(0编辑  收藏  举报