druiddatasource配置_Springboot属性注入 Java配置和Value配置
今天我们正式进入了SpringBoot入门实战系列的课程,第二个部分SpringBoot配置和日志管理,本期课程将会分享:1.springboot属性注入 - @Value(推荐);2.Springboot属性注入 - Java代码方式配置.
1.springboot属性注入 - @Value(推荐)
目标:
可以使用@Value获取配置文件配置application.properties
分析:
1: 在application.properties中定义:
# 当前tomcat默认端口server.port=8089# 自定义属性user.username=zhangsan2:在 UserController中使用@Value 注解获取
@RestControllerpublic class UserController { @Value("${user.username}") private String username; @RequestMapping("/test") public String index(){ return "success"+username; }}3:访问:http://localhost:8089/test:
结果是:success zhangsan
2. springboot属性注入 - Java代码方式配置
目标:
可以使用@Value获取配置文件配置项并结合@Bean注册组件到Spring
分析:
使用Java代码配置数据库连接池,并可以在处理器中注入并使用
步骤:
1、添加依赖;
mysql mysql-connector-java 5.1.10 com.alibaba druid-spring-boot-starter 1.1.18 org.springframework.boot spring-boot-starter-jdbc2、创建数据库;任意找一个数据库
3、创建数据库连接参数的配置文件jdbc.properties;
# 自定义属性jdbc.url=jdbc:mysql://localhost:3306/kekeblog?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=falsejdbc.username=rootjdbc.password=mkxiaoerjdbc.driverClassName=com.mysql.jdbc.Driver4、创建配置类;
package com.itheima.config;import com.alibaba.druid.pool.DruidDataSource;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.PropertySource;import javax.sql.DataSource;@Configuration@PropertySource("classpath:jdbc.properties")public class JdbcConfig { @Value("${jdbc.url}") String url; @Value("${jdbc.driverClassName}") String driverClassName; @Value("${jdbc.username}") String username; @Value("${jdbc.password}") String password; @Bean public DataSource dataSource(){ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; }}小结
使用@Value 注入属性值的时候,注意的key的名字必须和属性文件jdbc.properties保持高度一致,不支持驼峰命令的缩写规则。
回复关键词
Redis 分布式限流 MySQL alibaba JVM性能调优
看更多精彩教程
喜欢本文,记得点击个在看,或者分享给朋友哦!
总结
以上是生活随笔为你收集整理的druiddatasource配置_Springboot属性注入 Java配置和Value配置的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 为什么单击用户账户没有反应_为什么您的网
- 下一篇: 6. 以下耦合度中最松散的耦合是_Spr