码迷,mamicode.com
首页 > 编程语言 > 详细

使用springboot配置和注入数据源属性的方法和步骤

时间:2019-12-16 14:50:08      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:数据   stc   framework   col   import   cto   ica   map   url   

  /**

    1、书写一个名为resources/application.properties的属性文件---->书写一个配置属性类,类名为:

**/

    文件:application.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.28.128
jdbc.username=orcl
jdbc.password=123456

文件:JdbcProperties
package com.hope.config;

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

/**
* @author newcityman
* 使用lombok插件
* @date 2019/12/16 - 0:59
*/
@ConfigurationProperties(prefix = "jdbc")
@Data
public class JdbcProperties {
String driverClassName;
String url;
String username;
String password;
}

package com.hope.config;

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

import javax.sql.DataSource;

/**
* @author newcityman
* @Bean 把类的返回值注入到spring核心容器便于调用
* @date 2019/12/15 - 23:52
*/
@Configuration
/*@PropertySource("classpath:application.properties")*/
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
@Bean
public DataSource dataSource(JdbcProperties jp){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(jp.getDriverClassName());
dataSource.setUrl(jp.getUrl());
dataSource.setUsername(jp.getUsername());
dataSource.setPassword(jp.getPassword());
return dataSource;
}
}

package com.hope;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;

/**
* @author newcityman
* @date 2019/12/15 - 23:09
*/
@SpringBootApplication
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BootDemoApplication.class,args);
}
}

package com.hope.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

/**
* @author newcityman
* @date 2019/12/15 - 23:28
*/
@RestController
public class HelloController {
@Autowired
private DataSource dataSource;

@GetMapping("hello")
@ResponseBody
public String Hello(){
return "hello zmy,你好";
}
}
 
 
 
 

使用springboot配置和注入数据源属性的方法和步骤

标签:数据   stc   framework   col   import   cto   ica   map   url   

原文地址:https://www.cnblogs.com/newcityboy/p/12049026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!