zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    JAVA基础知识之多线程——线程通信
    为Apache配置虚拟机Virtual Host
    SignalR的坑爹细节
    ashx入侵
    aspnet5安装ef7备忘
    aspnet5备忘
    NHibernate初步使用
    MVC中发生System.Data.Entity.Validation.DbEntityValidationException验证异常的解决方法
    关于NLog的target和Layout
    泛型约束的大概模样
  • 原文地址:https://www.cnblogs.com/yanweifeng/p/13377271.html
Copyright © 2011-2022 走看看