/**
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,你好";
}
}