1. 开发工具:IntelliJ IDEA
2. 百度搜索--IntelliJ IDEA--Ultimate版本
3. lanyu注册码:淘宝上购买JetBrain全家桶
4. 安装教程:https://www.runoob.com/w3cnote/intellij-idea-usage.html
http://idea.lanyus.com/
替换内容:现将host复制出来
0.0.0.0 account.jetbrains.com
0.0.0.0 www.jetbrains.com
创建一个springboot工程
如果计算机中已经有了Maven,IntelliJ自带的内置的Maven插件,在当前计算机的目录下
C:\Users\Administrator\.m2\repository
spring boot官网:
https://spring.io/projects/spring-boot/
https://start.spring.io/
IDE连接数据库详细步骤:
.idea目录和.mvn目录与开发工具有关,不是源码
修改IDE中字体的大小
利用鼠标的滚轮控制字体大小
课后作业:需要在application.properties文件中配置
#前台表单提交字符串转换为Date
spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
#后台的Date类型转换指定格式的字符串在json当中
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
正常情况:蓝色的文件夹--java文件 | 绿色的文件夹--test测试文件
如果文件夹没有颜色,说明不是Maven工程,进行修改:
工程连接数据库进行访问:
控制台打印结果:
package com.neuedu.demo1.model;
import java.util.Date;
public class Book {
// 包装类和基本数据类型的区别
private Integer bookNo;
private String bookName;
private String author;
private Date date;
// 快速生成构造函数和get、set方法
// 快捷键:alt+enter(单独生成单个属性,鼠标定位)
// alt+insert(批量创建),shift+上下选中回车
public Integer getBookNo() {
return bookNo;
}
public void setBookNo(Integer bookNo) {
this.bookNo = bookNo;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Book(Integer bookNo, String bookName, String author, Date date) {
this.bookNo = bookNo;
this.bookName = bookName;
this.author = author;
this.date = date;
}
public Book() {
}
}
Lombok的优点:以简单的注解形式来简化java代码,提高开发人员的开发效率
1.Lombok自动生成实体类中的get/set/toString等方法
<scope>providedscope>的含义是:只在编译期起作用
2.在Pom.xml文件中添加依赖:
https://mvnrepository.com/artifact/org.projectlombok/lombok/1.18.8
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.8version>
<scope>providedscope>
dependency>
3.使IntelliJ使用默认的仓库和本地的Maven仓库合并
4.使用lombok
// 1.在项目当中引入lombok依赖,作用域:provided(只在编译器,不会被打包进项目)
// 2.给IDE装lombok插件
package com.neuedu.demo1.model;
//import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
//import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data public class Book {
// 包装类和基本数据类型的区别
private Integer bookNo;
private String bookName;
private String author;
// // 方式二:日期格式转换
// // 局部配置优先于全局配置
// @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
//// @JsonFormat(timezone = "GMT+8",pattern = "yyyy/MM/dd")
private Date publishDate;
//
// // 快速生成构造函数和get、set方法
// // 快捷键:alt+enter(单独生成单个属性,鼠标定位)
// // alt+insert(批量创建),shift+上下选中回车
//
// public Book() {
// }
//
// public Book(Integer bookNo, String bookName, String author, Date publishDate) {
//
// this.bookNo = bookNo;
// this.bookName = bookName;
// this.author = author;
// this.publishDate = publishDate;
// }
//
// public Integer getBookNo() {
//
// return bookNo;
// }
//
// public void setBookNo(Integer bookNo) {
// this.bookNo = bookNo;
// }
//
// public String getBookName() {
// return bookName;
// }
//
// public void setBookName(String bookName) {
// this.bookName = bookName;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public Date getPublishDate() {
// return publishDate;
// }
//
// public void setPublishDate(Date publishDate) {
// this.publishDate = publishDate;
// }
}
package com.neuedu.demo1.controller;
import com.neuedu.demo1.model.Book;
import com.neuedu.demo1.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookController {
@Autowired
private BookService bookService;
// 请求路径/book/1001
@RequestMapping("/book/{id}")
public Book findBook(@PathVariable("id") Integer id){
Book book = new Book();
book.getAuthor();
// 1.在项目当中引入lombok依赖,作用域:provided(只在编译器,不会被打包进项目)
// 2.给IDE装lombok插件
return bookService.findBookById(id);
}
}
在edit configuration 中修改 on update action 属性的值为:hot swap classes and update trigger File if failed
方式一的缺点:在类中添加新的方法时,报错
理由:java类都是编译生成字节码文件,新的方法字节码文件中不存在
方式二优点:新增方法也可以进行编译运行
全局重新编译--速度较慢
ctrl+shift+A快速搜索设置项
方式二详细步骤:
通过springboot devtools配置热重启
1. 将springboot devtools依赖包引入项目依赖中,通过pom
2. 在intellij 中配置complier的build project automatically为true
3. ctrl+shift+a(快速搜索设置项)搜索 registry,设置属性
complier.automake.allow.when.app.running 为true
在eclipse中直接引入devtools即可
在eclipse中只需要添加pom依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
java config 的几个注解与xml配置的对应关系
@Configuration 对应一个xml配置文件
@Bean 对应xml中的<bean>标签
@ComponentScan 对应xml 中的<context:component-scan>
@Scope注解对应<bean scope="">的属性
@Import注解对应<import>
@PropertyResource注解对应xml中的<context:property-placeholder>注解
@ImportResource 注解可以引入xml文件,将javaconfig 和xmlconfig结合使用,
application.yml
#server:
# port: 8080
# servlet:
# context-path: /demo1
# 设置日志等级
logging:
level:
org:
springframework: debug
com:
neuedu: debug
# 生成的日志文件路径
file: d:/
package com.neuedu.demo1.controller;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
//@Controller
public class HelloController {
private static Logger logger = LoggerFactory.getLogger(HelloController.class);
// @ResponseBody
@GetMapping("/hello")
public String hello(){
logger.debug("hello Log");
// 返回的是一个逻辑ModelAndView视图名称
return "{\"content\":\"hello Spring Boot 热部署!!\"}";
}
}
application-dev.yml
server:
port: 8080
application-prod.yml
server:
port: 8888
application.yml
# 实现在多个环境下进行切换
# 没有配置,默认是8080
# prod生产环境和开发环境Dev(名字可以改变)
# 新建两个application-dev和application-prod的文件
# application是spring的固定格式
profiles:
active: prod
com.neuedu.demo1.interceptor.AuthInterceptor
package com.neuedu.demo1.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 拦截器
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String username = (String) request.getSession().getAttribute("username");
if(username != null && !"".equals(username)){
return true;
}
response.getWriter().print("Access denied!");
return false;
}
}
com.neuedu.demo1.config.AppConfig
package com.neuedu.demo1.config;
import com.neuedu.demo1.interceptor.AuthInterceptor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootConfiguration
public class AppConfig implements WebMvcConfigurer {
// 拦截所有的请求/**,除了/login
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login/*");
}
}
主流的前后端分离的基于JavaScript 的mvvm框架:
vue.js(简易) react.js(强大,学习成本高) augluar.js ext.js ember.js
分布式框架:dubbo(阿里使用的框架)
学习:Redis、JPA、GSON、thymeleaf
package com.neuedu.demo1.config;
import com.neuedu.demo1.interceptor.AuthInterceptor;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@SpringBootConfiguration
public class AppConfig implements WebMvcConfigurer {
// 拦截所有的请求/**,除了/login
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login/*");
}
}
package com.neuedu.demo1.controller;
import com.neuedu.demo1.model.Book;
import com.neuedu.demo1.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BookController {
@Autowired
private BookService bookService;
// 请求路径/book/1001
@RequestMapping("/book/{id}")
public Book findBook(@PathVariable("id") Integer id){
Book book = new Book();
book.getAuthor();
// 1.在项目当中引入lombok依赖,作用域:provided(只在编译器,不会被打包进项目)
// 2.给IDE装lombok插件
return bookService.findBookById(id);
}
}
package com.neuedu.demo1.controller;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
//@Controller
public class HelloController {
private static Logger logger = LoggerFactory.getLogger(HelloController.class);
// @ResponseBody
@GetMapping("/hello")
public String hello(){
logger.debug("hello Log");
// 返回的是一个逻辑ModelAndView视图名称
return "{\"content\":\"hello Spring Boot 热部署!!\"}";
}
@GetMapping("/hi")
public String hi(){
return "hi springboot hot";
}
@RequestMapping("/login/{username}")
public String login(@PathVariable("username") String username, HttpSession session) throws Exception{
session.setAttribute("username",username);
return "login success";
}
}
package com.neuedu.demo1.dao;
import com.neuedu.demo1.model.Book;
//import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Repository
public interface BookDao {
// @Select("select bNo as bookNo,bName as bookName,author,publishDate from book where bNo=#{id}")
Book findBookById(Integer id) ;
}
package com.neuedu.demo1.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 拦截器
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String username = (String) request.getSession().getAttribute("username");
if(username != null && !"".equals(username)){
return true;
}
response.getWriter().print("Access denied!");
return false;
}
}
package com.neuedu.demo1.model;
//import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
//import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data public class Book {
// 包装类和基本数据类型的区别
private Integer bookNo;
private String bookName;
private String author;
// // 方式二:日期格式转换
// // 局部配置优先于全局配置
// @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
//// @JsonFormat(timezone = "GMT+8",pattern = "yyyy/MM/dd")
private Date publishDate;
//
// // 快速生成构造函数和get、set方法
// // 快捷键:alt+enter(单独生成单个属性,鼠标定位)
// // alt+insert(批量创建),shift+上下选中回车
//
// public Book() {
// }
//
// public Book(Integer bookNo, String bookName, String author, Date publishDate) {
//
// this.bookNo = bookNo;
// this.bookName = bookName;
// this.author = author;
// this.publishDate = publishDate;
// }
//
// public Integer getBookNo() {
//
// return bookNo;
// }
//
// public void setBookNo(Integer bookNo) {
// this.bookNo = bookNo;
// }
//
// public String getBookName() {
// return bookName;
// }
//
// public void setBookName(String bookName) {
// this.bookName = bookName;
// }
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public Date getPublishDate() {
// return publishDate;
// }
//
// public void setPublishDate(Date publishDate) {
// this.publishDate = publishDate;
// }
}
package com.neuedu.demo1;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.neuedu.demo1.dao")
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
<mapper namespace="com.neuedu.demo1.dao.BookDao">
<select id="findBookById" resultType="com.neuedu.demo1.model.Book">
select
bNo as bookNo,
bName as bookName,
author,
publishDate
from book where bNo = #{id}
select>
mapper>
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/mysqldb?useUnicode=true&characterEncoding=utf8
#spring.datasource.username=root
#spring.datasource.password=root123
#
#mybatis.mapper-locations=classpath:/mappers/*.xml
#
##前端页面传入的时间字符串无法自动转换成日期格式(针对json格式)
#spring.mvc.date-format=yyyy-MM-dd HH:mm:ss
#
##后台Date类型转换成指定格式的字符串在Json中
#spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#spring.jackson.time-zone=GMT+8
#
##server.port=8081
#properties和yml作用相同 格式不同
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mysqldb?useUnicode=true&characterEncoding=utf8
username: root
password: root123
mvc:
date-format: yyyy-MM-dd HH:mm:ss
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
# 实现在多个环境下进行切换
# 没有配置,默认是8080
# prod生产环境和开发环境Dev(名字可以改变)
# 新建两个application-dev和application-prod的文件
# application是spring的固定格式
profiles:
active: prod
mybatis:
mvc:
date-format: yyyy-MM-dd HH:mm:ss
mapper-locations: classpath:/mappers/*.xml
#server:
# port: 8080
# servlet:
# context-path: /demo1
# 设置日志等级
logging:
level:
org:
springframework: debug
com:
neuedu: debug
# 生成的日志文件路径
file: d:/
server:
port: 8080
server:
port: 8888
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.1.6.RELEASEversion>
<relativePath/>
parent>
<groupId>com.neuedugroupId>
<artifactId>demo1artifactId>
<version>0.0.1-SNAPSHOTversion>
<name>demo1name>
<description>Demo project for Spring Bootdescription>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.0.1version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<scope>providedscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
1.新建一个普通的Maven工程
2.配置本地仓库和pom中所需要的依赖
新建Maven工程步骤:File--New--Project--Maven--groupID&artifactId--jdk版本--Finish(可参照上面Demo1示例图)
springBoot:
省略了web.xml默认采用的Servlet的是3.0版本
spring.xml文件省略
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.swh.demogroupId>
<artifactId>springboot-demoartifactId>
<version>1.0.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.4.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>
project>
package cn.swh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// springBoot启动的注解@SpringBootApplication
@SpringBootApplication
public class BootDemoApplication {
public static void main(String args[]){
SpringApplication.run(BootDemoApplication.class,args);
}
}
package cn.swh.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//这里使用RestController可以替换@Controller和@ResponseBody
@Controller
public class HelloController {
@GetMapping("hello")
// 返回的是一个数据添加@ResponseBody注解
@ResponseBody
public String hello(){
return "hello,spring boot!";
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.swh.demogroupId>
<artifactId>springboot-demoartifactId>
<version>1.0.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.4.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.10version>
dependency>
dependencies>
project>
package cn.swh.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;
// 声明一个类作为配置类,代替原来spring中配置的数据源...
// 增强代码的可读性
@Configuration
// PropertySource引入外部文件
@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;
}
}
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/swh
jdbc.username=root
jdbc.password=root123
package cn.swh.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.sql.DataSource;
@Controller
public class HelloController {
@Autowired
private DataSource dataSource;
@GetMapping("hello")
// 返回的是一个数据添加@ResponseBody注解
@ResponseBody
public String hello(){
return "hello,spring boot!";
}
}
package cn.swh.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
//配置属性
@ConfigurationProperties(prefix = "jdbc")
// 编译时自动生成get、set、hashCode、toString方法
@Data
public class JdbcProperties {
/**
* 这里定义的属性值要与application。properties中的属性名称完全一致
*/
String url;
String driverClassName;
String username;
String password;
// 添加lombok依赖,简写setget方法
// 添加@Data注解
}
package cn.swh.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
// 声明一个类作为配置类,代替原来spring中配置的数据源...
// 增强代码的可读性
@Configuration
// PropertySource引入外部文件
//@PropertySource("classpath:application.properties")
// 使用配置属性
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
//// 注入方式一:
// private JdbcProperties jdbcProperties;
//// 注入方式二:构造函数
// public JdbcConfig(JdbcProperties jdbcProperties){
// this.jdbcProperties = jdbcProperties;
// }
@Bean
// 注入方式三:方法注入
public DataSource dataSource(JdbcProperties prop){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(prop.getDriverClassName());
dataSource.setUrl(prop.getUrl());
dataSource.setUsername(prop.getUsername());
dataSource.setPassword(prop.getPassword());
return dataSource;
}
}
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/swh
jdbc.username=root
jdbc.password=root123
package cn.swh.config;
import lombok.Data;
//配置属性
//@ConfigurationProperties(prefix = "jdbc")
// 编译时自动生成get、set、hashCode、toString方法
@Data
public class JdbcProperties {
/**
* 这里定义的属性值要与application。properties中的属性名称完全一致
*/
String url;
String driverClassName;
String username;
String password;
// 添加lombok依赖,简写setget方法
// 添加@Data注解
}
package cn.swh.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
// 声明一个类作为配置类,代替原来spring中配置的数据源...
// 增强代码的可读性
@Configuration
// PropertySource引入外部文件
//@PropertySource("classpath:application.properties")
// 使用配置属性
//@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
//// 注入方式一:
// private JdbcProperties jdbcProperties;
//// 注入方式二:构造函数
// public JdbcConfig(JdbcProperties jdbcProperties){
// this.jdbcProperties = jdbcProperties;
// }
// @Bean
// 注入方式三:方法注入
// public DataSource dataSource(JdbcProperties prop){
// DruidDataSource dataSource = new DruidDataSource();
// dataSource.setDriverClassName(prop.getDriverClassName());
// dataSource.setUrl(prop.getUrl());
// dataSource.setUsername(prop.getUsername());
// dataSource.setPassword(prop.getPassword());
// return dataSource;
// }
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource dataSource(){
return new DruidDataSource();
}
}
项目中存在application.properties和application.yaml默认取二者并集
jdbc:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/swh
username: root
password: root123
user:
name: jack
age: 21
language:
- java
- php
- ios
- python
package cn.swh.config;
import lombok.Data;
import java.util.List;
//配置属性
//@ConfigurationProperties(prefix = "jdbc")
// 编译时自动生成get、set、hashCode、toString方法
@Data
public class JdbcProperties {
/**
* 这里定义的属性值要与application。properties中的属性名称完全一致
*/
String url;
String driverClassName;
String username;
String password;
User user = new User();
// 添加lombok依赖,简写setget方法
// 添加@Data注解
class User{
String name;
int age;
List<String> languages;
}
}