==和equals和hashCode

==和equals == 基本类型:比较的是值是否相同; 引用类型:比较的是内存地址是否相同(是否是同一对象); equals Object类中的equals方法 public boolean equals(Object obj) { return (this == obj); } String类重写了equals方法 public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; } 举例: ...

July 28, 2019 · 4 min · zhangxiaofeng05

java IO流

从控制台输入输出 import java.util.Scanner; public class IoTest { public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(n); String s = sc.next(); System.out.println(s); String line = sc.nextLine(); System.out.println(line);//从控制台输出 } } 字节流 FileOutputStream import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; public class IoTest { public static void main(String args[]){ File file = new File("aa.txt"); try { //FileOutputStream(File,boolean) 是否把内容追加 OutputStream out = new FileOutputStream(file); String str = "Hello World"; byte[] b=str.getBytes(); out.write(b); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } FileInputStream import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class IoTest { public static void main(String args[]){ try { File file = new File("E:"+File.separator+"tt.txt"); InputStream is = new FileInputStream(file); // byte[] bytes = new byte[1024]; //也可以这样 byte[] bytes = new byte[(int) file.length()]; is.read(bytes); System.out.println(new String(bytes)); //关闭流 is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } BufferedOutputStream import java.io.*; public class IoTest { public static void main(String args[]){ File file = new File("aa.txt"); try { OutputStream out = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(out); byte[] bytes = "土豆,土豆,呼叫土豆".getBytes(); bos.write(bytes); //刷新缓存 bos.flush(); bos.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } BufferedInputStream import java.io.*; public class IoTest { public static void main(String args[]){ try { File file = new File("E:"+File.separator+"tt.txt"); InputStream is = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(is); byte[] bytes = new byte[(int) file.length()]; bis.read(bytes); System.out.println(new String(bytes)); bis.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } 字符流 FileWriter import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; public class IoTest { public static void main(String args[]){ try { File file = new File("aa.txt"); Writer writer = new FileWriter(file); writer.write("土豆。。。\n"); writer.write("地瓜,对不起"); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } FileReader import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; public class IoTest { public static void main(String args[]){ try { File file = new File("aa.txt"); Reader reader = new FileReader(file); char[] chars = new char[1024]; reader.read(chars); System.out.println(new String(chars)); reader.close(); } catch (IOException e) { e.printStackTrace(); } } } 转换流(字节流转字符流) OutputStreamWriter import java.io.*; public class IoTest { public static void main(String args[]){ File file = new File("aa.txt"); try { OutputStream out = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(out); osw.write("这是字节流转成了字符流"); String encoding = osw.getEncoding(); System.out.println("文件的编码:"+encoding); //文件的编码:UTF8 osw.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } InputStreamReader import java.io.*; public class IoTest { public static void main(String args[]){ try { File file = new File("aa.txt"); InputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is,"utf-8");//指定编码 char[] chars = new char[1024]; isr.read(chars); System.out.println(chars); System.out.println("编码:"+isr.getEncoding()); isr.close(); isr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } 字符缓冲流(高效流) BufferedWriter import java.io.*; public class IoTest { public static void main(String args[]){ File file = new File("aa.txt"); try { OutputStream out = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(out); BufferedWriter bw = new BufferedWriter(osw); bw.write("hello 这是字符缓冲流"); bw.newLine(); bw.write("下一行"); bw.close(); osw.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } BufferedReader import java.io.*; public class IoTest { public static void main(String args[]){ try { File file = new File("aa.txt"); InputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is,"utf-8"); BufferedReader br = new BufferedReader(isr); String str; while ((str=br.readLine())!=null){ System.out.println(str); } br.close(); isr.close(); is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } 字节流与字符流的区别 字节流在操作的时候本身是不会用到缓冲区(内存)的,是与文件本身直接操作的,而字符流在操作的时候是使用到缓冲区的 ...

July 25, 2019 · 3 min · zhangxiaofeng05

java异常

异常类型 检查性异常 最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。 运行时异常 运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略(Throw)。 错误 错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。 异常类Exception 构造方法 public Exception() 构建一个新的异常,以 null作为其详细信息。 public Exception(String message) 使用指定的详细消息构造新的异常。 public Exception(String message, Throwable cause) 构造一个新的异常与指定的详细信息和原因。 public Exception(Throwable cause) 构造一个新的异常与指定原因。 protected Exception(String message, Throwable cause,boolean enableSuppression,boolean writableStackTrace) 构造一个新的异常,其中包含指定的详细消息,启用或禁用抑制功能,启用或禁用可写栈跟踪。 常用方法 public String getMessage() 返回关于发生的异常的详细信息。这个消息在Throwable 类的构造函数中初始化了。 public Throwable getCause() 返回一个Throwable 对象代表异常原因。 public String toString() 使用getMessage()的结果返回类的串级名字。 public void printStackTrace() 打印toString()结果和栈层次到System.err,即错误输出流。 public StackTraceElement [] getStackTrace() 返回一个包含堆栈层次的数组。下标为0的元素代表栈顶,最后一个元素代表方法调用堆栈的栈底。 public Throwable fillInStackTrace() 用当前的调用栈层次填充Throwable 对象栈层次,添加到栈层次任何先前信息中。 处理异常 try-catch public class MyException extends Exception{ public static void main(String[] args) { try { int i=1/0; }catch (ArithmeticException e){ e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); System.out.println("这是总异常"); }finally { System.out.println("无论有没有异常,都会执行。比如用于关闭数据库的连接"); } } } throws public class MyException extends Exception{ public static void main(String[] args) { MyException myException = new MyException(); try { myException.show(); } catch (Exception e) { e.printStackTrace(); } } public void show() throws Exception{//抛出去,谁调用谁处理 int i=1/0; } } 注意事项 throws在方法名后边 catch 不能独立于 try 存在。 在 try/catch 后面添加 finally 块并非强制性要求的。 try 代码后不能既没 catch 块也没 finally 块。 try, catch, finally 块之间不能添加任何代码。 ...

July 25, 2019 · 1 min · zhangxiaofeng05

Java中Date、SimpleDateFormat、Calendar

jdk1.8 import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Java 语言的Date(日期),Calendar(日历),DateFormat(日期格式)组成了Java标准的一个基本但是非常重要的部分。 */ public class StringTest { public static void main(String[] args) throws ParseException { Date currentTime = new Date(); System.out.println(currentTime); //设置时间格式 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(simpleDateFormat.format(currentTime)); SimpleDateFormat year = new SimpleDateFormat("yyyy");//获取年----其它类似 System.out.println(year.format(currentTime)); Date date = simpleDateFormat.parse("2019-1-23 12:00:00");//把字符串转换成日期 System.out.println(simpleDateFormat.format(date)); //计算时间差currentTime-date相差多少天 Long days = (currentTime.getTime()-date.getTime())/(1000*60*60*24);//参数--毫秒 System.out.println(days); System.out.println("---------------------------利用Calendar获取时间值比较方便"); // Calendar转化为Date Calendar cal=Calendar.getInstance(); Date date1=cal.getTime(); // Date转化为Calendar Calendar cal2=Calendar.getInstance(); cal2.setTime(date); //计算某个日期是那一年的第几天 int d = cal2.get(Calendar.DAY_OF_YEAR); System.out.println(d); //一年的第几周等。。 } }

July 24, 2019 · 1 min · zhangxiaofeng05

String、StringBuffer、StringBuilder的区别

长度是否可变 String 是被 final 修饰的,他的长度是不可变的,就算调用 String 的concat 方法,那也是把字符串拼接起来并重新创建一个对象,把拼接后的 String 的值赋给新创建的对象 StringBuffer 和 StringBuilder修改本身 执行效率 三者在执行速度方面的比较:StringBuilder > StringBuffer > String 应用场景 如果要操作少量的数据用 = String 单线程操作字符串缓冲区 下操作大量数据 = StringBuilder 多线程操作字符串缓冲区 下操作大量数据 = StringBuffer 线程安全 StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问),StringBuffer是线程安全的。只是StringBuffer 中的方法大都采用了 synchronized 关键字进行修饰,因此是线程安全的,而 StringBuilder 没有这个修饰,可以被认为是线程不安全的。 参考 https://www.cnblogs.com/AmyZheng/p/9415064.html

July 24, 2019 · 1 min · zhangxiaofeng05

Java中的线程

进程和线程概念 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。进程是线程的容器。 线程(thread)是操作系统能够进行运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位。一个进程中可以并发多个线程,每条线程并行执行不同的任务。 同一进程中的多条线程将共享该进程中的全部系统资源,如虚拟地址空间,文件描述符和信号处理等等。但同一进程中的多个线程有各自的调用栈(call stack),自己的寄存器环境(register context),自己的线程本地存储(thread-local storage)。 一个进程可以有很多线程,每条线程并行执行不同的任务。 线程 在 Java程序中,有两种方法创建线程: 一继承Thread重写run方法 二是通过实现Runnable接口,实现run方法 线程总体分两类:用户线程和守候线程。 当所有用户线程执行完毕的时候,JVM自动关闭。但是守候线程却不独立于JVM,守候线程一般是由操作系统或者用户自己创建的。 继承Thread public class ThreadOne extends Thread{ private String name; public ThreadOne() { } public ThreadOne(String name) { this.name = name; } @Override public void run() { for(int i=1;i<=10;i++){ System.out.println(name+"----"+i); } } } public class ThreadTest { public static void main(String[] args) { ThreadOne threadOne1 = new ThreadOne("地瓜"); ThreadOne threadOne2 = new ThreadOne("土豆"); threadOne1.start(); threadOne2.start(); } } 实现Runnable接口 public class ThreadTwo implements Runnable { private String name; public ThreadTwo() { } public ThreadTwo(String name) { this.name = name; } @Override public void run() { for(int i=1;i<=10;i++){ System.out.println(name+"-------"+i); } } } public class ThreadTest { public static void main(String[] args) { Thread t1 = new Thread(new ThreadTwo("地瓜")); Thread t2 = new Thread(new ThreadTwo("土豆")); t1.start(); t2.start(); } } 线程的转换 新建状态:线程对象已经创建 就绪状态:执行了start 运行状态:线程调度程序从可运行池中选择一个线程作为当前线程时线程所处的状态。这也是线程进入运行状态的唯一一种方式。 阻塞:线程仍旧是活的,但是当前没有条件运行。 死亡态:当线程的run()方法完成时就认为它死去。这个线程对象也许是活的,但是,它已经不是一个单独执行的线程。线程一旦死亡,就不能复生。如果在一个死去的线程上调用start()方法,会抛出java.lang.IllegalThreadStateException异常。 ...

July 24, 2019 · 1 min · zhangxiaofeng05

Spring Boot打印日志

本文环境 jdk 1.8 maven 3.6.1 Spring Boot 2.1.6 SLF4J 为什么要介绍SLF4J? SLF4J是一个接口,log4j和logback是它的实现。 SLF4J官网:https://www.slf4j.org 官网示例 引入jar包 slf4j-api-1.7.26.jar slf4j-simple-1.7.26.jar 编写测试类(Java Project) import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HelloWorld { public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.info("Hello World"); } } 有什么问题,去官网查看示例! Spring Boot中使用日志(logback) 编写测试类 import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class LogbackTest { //记录器 Logger logger = LoggerFactory.getLogger(getClass()); @Test public void logTest() { //日志的级别 //从上到下---由低到高 //日志会在设置的级别和高级别生效,Spring Boot默认info logger.trace("这是trace日志..."); logger.debug("这是debug日志..."); //可以在logback-spring.xml或者在application.xml配置日志级别 logger.info("这是info日志..."); logger.warn("这是warn日志..."); logger.error("这是error日志..."); } } 设置日志的格式 resources/logback-spring.xml <?xml version="1.0" encoding="UTF-8"?> <configuration debug="false" scan="true" scanPeriod="60 seconds"> <!--定义日志文件的存储地址 勿在 LogBack 的配置中使用相对路径 --> <!-- <property name="LOG_PATH" value="/data/log/process/springboot-demo" /> --> <springProperty name="LOG_PATH" source="logging.path" defaultValue="../logs" /> <!-- 控制台输出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 --> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> </encoder> </appender> <!-- 按照每天生成日志文件 --> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--日志文件输出的文件名 --> <FileNamePattern>${LOG_PATH}/log.log.%d{yyyy-MM-dd}</FileNamePattern> <!--日志文件保留天数 --> <!-- <MaxHistory>30</MaxHistory> --> </rollingPolicy> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 --> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> </encoder> </appender> <!-- 日志输出级别 --> <root level="INFO"> <appender-ref ref="FILE" /> <appender-ref ref="STDOUT" /> </root> </configuration> 配置文件的加载顺序 application.properties或者application.yml文件作为Spring Boot的默认配置文件 ...

July 20, 2019 · 1 min · zhangxiaofeng05

Spring Boot发送邮件

本文环境 jdk 1.8 maven 3.6.1 Spring Boot 2.1.6 引入依赖 pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> 在application.properties中添加邮件配置(以QQ邮箱为例) spring.mail.host=smtp.qq.com spring.mail.port=587 spring.mail.username=xxx@qq.com spring.mail.password=授权码 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true spring.mail.default-encoding=UTF-8 mail.fromMail.addr=xxx@qq.com #发送来源,和账户相同 QQ邮箱的服务器端口 接收邮件服务器:imap.qq.com,使用SSL,端口号993 发送邮件服务器:smtp.qq.com,使用SSL,端口号465或587 QQ邮箱帮助中心 编写Service接口 public interface MailService { public void sendSimpleMail(String to,String subject,String content); public void sendHtmlMail(String to, String subject, String content); public void sendAttachmentsMail(String to, String subject, String content, String filePath); } } 编写Service的实现类 import java.io.File; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; @Component public class MailServiceImpl implements MailService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String from; @Override public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); logger.info("简单邮件已经发送"); } catch (Exception e) { logger.error("发送简单邮件时发生异常!",e); } } @Override public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); logger.info("html邮件发送成功"); } catch (MessagingException e) { logger.error("发送html邮件时发生异常!", e); } } @Override public void sendAttachmentsMail(String to, String subject, String content, String filePath) { MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } } } 编写测试类 import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.boot.service.MailService; @RunWith(SpringRunner.class) @SpringBootTest public class MailTest { @Autowired private MailService mailService; @Test public void testSimple() { mailService.sendSimpleMail("xxx@163.com", "test simple mail", "hello this is simple mail"); } @Test public void testHtmlMail() throws Exception { String content="<html>\n" + "<body>\n" + " <h3>hello world ! 这是一封Html邮件!</h3>\n" + "</body>\n" + "</html>"; mailService.sendHtmlMail("xxx@163.com","test simple mail",content); } @Test public void sendAttachmentsMail() { String filePath="D:\\testMail.txt"; mailService.sendAttachmentsMail("xxx@163.com", "主题:带附件的邮件", "有附件,请查收!", filePath); } } 至此,邮件发送成功! ...

July 19, 2019 · 2 min · zhangxiaofeng05

request和Session

区别 request session 描述 一次请求(访问一个url) 一次对话(可以访问多个url) 作用 获取信息(表单,查询,cookie等信息) 记录变量(跟踪记录访问者动作) 作用端 浏览器 服务器 生命周期 提交以后即释放 关闭浏览器或者超出会话时间限制(maxInactiveIntervalInSeconds;The session timeout in seconds. By default, it is set to 1800 seconds (30 minutes).) 占用资源 比较少 相对较大 安全性 比较高 稍微低点

July 19, 2019 · 1 min · zhangxiaofeng05

Druid数据库连接池

阿里巴巴数据库事业部出品,为监控而生的数据库连接池。 托管于GitHub,项目地址 https://github.com/alibaba/druid Druid是一个JDBC组件库,包括数据库连接池、SQL Parser等组件。DruidDataSource是最好的数据库连接池。 Springboot使用 最新信息去GitHub Maven <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.17</version> </dependency> Gradle compile 'com.alibaba:druid-spring-boot-starter:1.1.17' 配置 Github上有说明,下面是一下常用配置 application.properties #mysql spring.datasource.platform=mysql spring.datasource.url=jdbc:mysql://localhost:3306/database?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=154704 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #druid spring.datasource.type=com.alibaba.druid.pool.DruidDataSource # Advanced configuration... spring.datasource.max-active=500 spring.datasource.min-idle=2 spring.datasource.initial-size=6 开启监测 DruidConfiguration 监测地址:http://localhost:8080/druid/index.html import javax.sql.DataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; @Configuration public class DruidConfiguration { @ConfigurationProperties("spring.datasource") @Bean public DataSource druidDataSource() { return new DruidDataSource(); } @Bean public ServletRegistrationBean<StatViewServlet> druidStatViewServlet() { ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); registrationBean.addInitParameter("allow", "127.0.0.1");// IP白名单 (没有配置或者为空,则允许所有访问) registrationBean.addInitParameter("deny", "");// IP黑名单 (存在共同时,deny优先于allow) registrationBean.addInitParameter("loginUsername", "root"); registrationBean.addInitParameter("loginPassword", "123456"); registrationBean.addInitParameter("resetEnable", "false"); return registrationBean; } } 测试类 import java.sql.Connection; import javax.sql.DataSource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootApplicationTests { @Autowired DataSource dataSource; @Test public void contextLoads() { } @Test public void test1() throws Exception { System.out.println(dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println(connection.getClass()); connection.close(); } }

July 18, 2019 · 1 min · zhangxiaofeng05