1,修改SpringBoot启动Banner图案
在resources目录下创建banner.txt文件,SpringBoot就会默认读取其中的内容作为Banner,当然也支持图片格式。
提供了改字体的网址:
Spring Boot banner在线生成工具,制作下载英文banner.txt,修改替换banner.txt文字实现自定义,个性化启动banner-bootschool.net 关闭banner的显示,在main方法中实现:
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
//SpringApplication.run(App.class,args);
SpringApplication application=new SpringApplication(App.class);
application.setBannerMode(Banner.Mode.OFF);
application.run(args);
}
}
2,SpringBoot中的属性注入方式
1,在SpringBoot的配置文件中配置属性
文件名:application.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/xa2304 jdbc.username=root jdbc.password=root |
2,创建一个属性配置类,读取配置文件的内容
@Data
@ConfigurationProperties(prefix ="jdbc")
public class JdbcProperties {
private String driver;
private String url;
private String username;
private String password;
}
3,创建一个SpringBoot配置类
ublic class JdbcConfig {
@Bean
@ConfigurationProperties(prefix = "jdbc") //Boot会自动将属性文件application.properties中的属性注入到DataSource中对应的属性上。
public DataSource dataSource(){
return new DruidDataSource();
}
}
4,运行测试类进行测试
@SpringBootTest
class Demo3ApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void contextLoads() {
System.out.println(dataSource);
}
}
3,yml配置方式
student: id: 2 name: 李四 age: 23 birthday: 1995/3/3 hobbys: - music - game - sport hobbys1: [music,game,sport] list: - xx - yy - zz map: cn: 中国 us: 美国 map1: {cn: 中国,us: 美国} |
4,SpringBoot自动配置原理
暂无
5,基于SpringBoot的注解验证
1,添加注解验证启动器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> |
2,使用验证注解编写实体类
@Data public class User { @NotBlank(message = "用户名不能为空!") @Length(min = 3,message = "用户名长度必须大于3位!") private String name; @NotNull(message = "年龄不能为空!") @Range(min = 0,max = 100,message = "年龄必须在0~100之间!") private Integer age; } |
3,编写控制器Controller
@RestController public class UserController { @RequestMapping("add") public String add(@Validated User user, BindingResult result){ if(result.hasErrors()){ return "数据非法,验证不通过!"; }else { System.out.println("添加。。。。。" + user); return "验证通过!"; } } } |
6,整合logback日志记录工具
在application.yml中修改日志级别:
logging: level: root: info #全局日志级别 com.bjpn: debug #局部日志级别 |
7,SpringBoot的静态资源访问
默认配置的访问路径的优先级:“META-INF/resources”---->“resources”----->“static”--->“public”
自定义静态资源的访问路径:
配置application.yml
spring: web: resources: static-locations: classpath:/myhtml/--------配置静态资源位置 mvc: static-path-pattern: /**-----------------匹配所有静态资源路径的模式 |
8,SpringBoot整合AOP开发
1,添加AOP启动器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> |
2,编写业务类
@Service
public class Man {
public String eat(String food){
System.out.println("吃"+food);
return food+"很好吃";
}
}
3,编写切面类
@Aspect
@Component
public class MyAspect {
public static final String POINT_CUT="execution(* com.bjpn.service.*.*(..))";
@Around(value = POINT_CUT)
public Object around(ProceedingJoinPoint pjp){
Object result=null;
try {
System.out.println("前置通知");
//执行目标业务方法
result = pjp.proceed();
System.out.println("后置通知");
} catch (Throwable e) {
System.out.println("异常通知");
}finally{
System.out.println("最终通知");
}
return result;
}
}
4,编写测试类
@SpringBootTest
class Demo5ApplicationTests {
@Autowired
private Man man;
@Test
void contextLoads() {
man.eat("油泼面...");
}
}
5,SpringBoot代理方式的切换
对于单例的对象,因为无需频繁创建对象,用 CGLib 合适,反之,使用 JDK 方式要更为合适一些。同时,由于 CGLib 由于是采用动态创建子类的方法,对于 final 方法,无法进行代理。
SpringBoot默认采用的是Cglib代理方式:
如果需要切换JDK代理方式,可以通过application.yml中配置如下:
spring: aop: proxy-target-class: false #默认true表示cglib代理方式,false为JDK代理方式 |
1,编写Eat接口
public interface Eat { String eat(String name); } |
2,编写Man类
@Service public class Man implements Eat { @Override public String eat(String food){ System.out.println("吃"+food); return food+"很好吃"; } } |
3,修改测试类
@SpringBootTest class Demo5ApplicationTests { @Autowired private Eat man; @Test void contextLoads() { System.out.println(man.getClass()); man.eat("油泼面..."); } } |
9,在SpringBoot中使用拦截器
1,编写Controller(需求:拦截add,放行show)
@RestController public class UserController { @RequestMapping("add") public String add(){ return "add"; } @RequestMapping("show") public String show(){ return "show"; } } |
2,创建拦截器
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("执行了拦截器..."); return true; } } |
3,在application.yml中配置拦截的url
myinterceptor: pathPatterns:----------拦截路径 - /add - /update excludePathPatterns:--------------不应用拦截路径 - /show - /find |
4,编写属性类,读取配置文件
@Data @ConfigurationProperties(prefix = "myinterceptor") @Component public class MvcProperties { private String[] pathPatterns; private String[] excludePathPatterns; } |
5,修改配置类
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Autowired private MvcProperties mvcProperties; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) .addPathPatterns(mvcProperties.getPathPatterns()) //拦截的url .excludePathPatterns(mvcProperties.getExcludePathPatterns()); //放行的url } } |
10,Web三大组件的注册
1,编写Servlet(不需要@WebServlet注解)
@Component
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print("HelloServlet...");
}
} |
2,编写过滤器Filter
@Component
public class AddFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
System.out.println("AddFilter...");
chain.doFilter(request, response);
}
} |
3,编写监听器Listener
@Component
public class MyListener implements ServletContextListener{
public MyListener() {
}
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("开启监听器");
/* This method is called when the servlet context is initialized(when the Web application is deployed). */
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("关闭监听器");
/* This method is called when the servlet Context is undeployed or Application Server shuts down. */
}
}
4,注册三大组件
@Configuration
public class MyServletRegistBean {
@Autowired
private HelloServlet helloServlet;
@Autowired
private AddFilter addFilter;
@Autowired
private MyListener myListener;
@Bean
@ConditionalOnClass(HelloServlet.class)
public ServletRegistrationBean<HelloServlet> servletRegistrationBean(){
ServletRegistrationBean regist = new ServletRegistrationBean();
regist.setServlet(helloServlet);
regist.addUrlMappings("/HelloServlet");
return regist;
}
@Bean
public FilterRegistrationBean<AddFilter> filterRegistrationBean(){
FilterRegistrationBean<AddFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(addFilter);
registrationBean.addUrlPatterns("/HelloServlet");
return registrationBean;
}
@Bean
public ServletListenerRegistrationBean<MyListener> ListenerRegistrationBean(){
ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>();
registrationBean.setListener(myListener);
return registrationBean;
}
}
11,SpringBoot整合JDBC和MyBatis
1,添加JDBC、druid连接池和mybatis相关依赖(分页插件)
jdbc依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> mysql依赖: <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> druid连接池依赖: <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.16</version> </dependency> mybatis依赖: <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> 分页插件pagehelper依赖:(必须1.4.1版本以上) <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.4.1</version> </dependency> |
2,配置application.yml文件
#数据源配置 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/xa2304?serverTimezone=Asia/Shanghai username: root password: root type: com.alibaba.druid.pool.DruidDataSource #修改连接池 --------------------------------------------------------------------------- #mybatis相关配置 mybatis: mapper-locations: classpath:mapper/*.xml #映射文件resources目录下 type-aliases-package: com.bjpn.pojo #类型别名 configuration: map-underscore-to-camel-case: true #驼峰命名配置 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #输出日志 |
12,SpringBoot的异步调用
1,异步调用概述:
在非spring目项目中我们要实现异步调用的就是使用多线程方式,可以自己实现Runable接口或者继承Thread类,或者使用jdk1.5以上提供了的Executors线程池。StrngBoot中则提供了很方便的方式执行异步调用(@Async)。
2,使用SpringBoot实现异步调用
1,使用@Async注解实现异步任务
@Service public class AsyncService { @Async public void task1(){ long begin=System.currentTimeMillis(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } long end=System.currentTimeMillis(); System.out.println("task1耗时:"+(end-begin)); } @Async public void task2(){ long begin=System.currentTimeMillis(); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } long end=System.currentTimeMillis(); System.out.println("task2耗时:"+(end-begin)); } @Async public void task3(){ long begin=System.currentTimeMillis(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } long end=System.currentTimeMillis(); System.out.println("task3耗时:"+(end-begin)); } } |
2,编写控制器Controller测试同步执行
@RestController public class UserController { @Autowired private AsyncService asyncService; @RequestMapping("doAsync") public String doAsync(){ long begin=System.currentTimeMillis(); asyncService.task1(); asyncService.task2(); asyncService.task3(); long end=System.currentTimeMillis(); return "总耗时:"+(end-begin); } } |
3,启动开启异步调用并测试
@SpringBootApplication @EnableAsync public class Demo10Application { public static void main(String[] args) { SpringApplication.run(Demo10Application.class, args); } } |
13,SpringBoot实现定时任务
1,添加定时任务的启动器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> |
2,编写定时任务类
@Scheduled(cron = "0 10 16 12 9 ?") ------------2023-9-12 16:10:00秒执行任务
注意:springboot的cron表达式必须有6位组成,不支持年份
@Service
public class MyTask {
@Scheduled(cron = "0 10 16 12 9 ?")
public void task(){
System.out.println(new Date());
}
}
3,启动类开启定时任务
@EnableScheduling
@SpringBootApplication
@EnableScheduling
public class Demo10Application {
public static void main(String[] args) {
SpringApplication.run(Demo10Application.class, args);
}
}
14,SpringBoot的邮件发送
1,添加mail的启动器
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> |
2,配置yml
确保邮箱的POP3/SMTP服务开启
spring: mail: default-encoding: utf-8 |
3,编写测试类发送邮件
@SpringBootTest
class Demo10ApplicationTests {
@Autowired
private JavaMailSender javaMailSender;
@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
// 发件人邮箱
simpleMailMessage.setFrom("liqun_han@126.com");
// 收件人邮箱
simpleMailMessage.setTo("liqun_han@126.com");
// 邮件主题
simpleMailMessage.setSubject("这是一个测试邮件");
// 邮件内容
simpleMailMessage.setText("测试内容");
javaMailSender.send(simpleMailMessage);
}
}
4,测试发送复杂内容,例如图片和附件等
@Test
void testSend2() throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
// 创建一个邮件工具,可以发送附件
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"utf-8");
mimeMessageHelper.setFrom("775610843@qq.com");
mimeMessageHelper.setTo("2270415677@qq.com");
mimeMessage.setSubject("这是一个携带了图片和附件的邮件");
//拼接内容参数
StringBuilder sb = new StringBuilder();
sb.append("<html> <body> <h1 style='color:red'>springboot 测试邮件发送复杂格式o</h1>");
sb.append("<p style='color:blue,font-size:16px'>哈哈哈</p>");
sb.append("<p style='text-align:center'>居中</p>");
sb.append("<img src='cid:picture'/> </body></html>"); //如果要插入图片src='cid:picture'
//设置内容,可以被html解析
mimeMessageHelper.setText(sb.toString(), true);
// 从本地磁盘中读取到图片 站位到内容中去
mimeMessageHelper.addInline("picture",new File("C:\\Users\\cxsxjw\\Pictures\\Saved Pictures\\abc.jpg"));
// 添加附件
mimeMessageHelper.addAttachment("测试文件.xls",new File("D:\\测试文件.xls"));
javaMailSender.send(mimeMessage);
}
15, springboot跨域访问
1,通过 @CrossOrigin 注解实现局部类跨域
@CrossOrigin(origins = "*")---------在控制器类前加注解
2, 通过设置配置文件实现全局跨域
@Configuration // 一定不要忽略此注解
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 所有接口
.allowCredentials(true) // 是否发送 Cookie
.allowedOriginPatterns("*") // 支持域
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}) // 支持方法
.allowedHeaders("*")//允许使用任何头信息进行跨域请求
.exposedHeaders("*");//允许在响应中返回任何头信息
}
}
3,通过 Response 实现局部方法跨域
在控制器方法后加:
response.setHeader("Access-Control-Allow-Origin", "*");