牛客网项目-第一章-笔记
牛客网项目-第一章
环境配置
java
maven
idea
Spring Intializr
搜索jar包的网站:https://mvnrepository.com/
https://start.spring.io/
缺少的aop包,手动在pom.xml中加入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
另外评论区中有人提到JPA底层也是aop实现的,可以导入这个用来代替aop。
下载解压后用idea打开
Spring boot 入门示例
一开始运行时有报错:
Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled.
2023-09-09T15:40:08.281+08:00 ERROR 34354 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : ***************************
APPLICATION FAILED TO START
***************************Description:Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.Reason: Failed to determine a suitable driver classAction:Consider the following:If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).Process finished with exit code 0
原因
这是因为spring boot 会默认加载org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
这个类DataSourceAutoConfiguration
类使用了@Configuration注解向spring注入了dataSource bean。因为工程中没有关于dataSource相关的配置信息,当spring创建dataSource bean因缺少相关的信息就会报错。
解决方法
在@SpringBootApplication
注解后面加上(exclude = {DataSourceAutoConfiguration.class})
增加功能
现在要在服务端提供一个功能,使其可以被浏览器访问到,能够给浏览器返回一个简短的问候。
新建一个包controller
controller下新建一个类
需要加两个springMVC的注解
@Controller
@RequestMapping("/alpha") //给这个类提供一个访问名称
还需要写一个能够给浏览器提供服务的方法。
@RequestMapping(/hello) //给方法也取一个访问路径,才能使其被访问到@ResponseBody//因为返回的不是网页,只是返回的普通字符串,还需要加一个注解进行声明public String sayHello(){return "Hello String Boot.";}
加了新的代码后需要重新编译重新启动。
点击Rerun,重新启动前会重新编译;或者也可以Build Project. 编译后自动重启是devtools的作用
运行后:
如何改端口和项目地址
在 .properties中修改配置信息
修改访问端口为8088
项目地址/community
server.port=8088
server.servlet.context-path=/community
更改后显示如下: