一、创建第一个helloword程序
- 打开idea,file-new-project-maven,设置GroupID 和ArtifactID
GroupID 是项目组织唯一的标识符,实际对应JAVA的包的结构,是main目录里java的目录结构。
ArtifactID是项目的唯一的标识符,实际对应项目的名称,就是项目根目录的名称。
在xml的project标签里中添加以下内容
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
注意如果下载jar包报错,在xml中添加以下内容解决,下载完成后在删掉
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2、编写一个主程序
// 标注一个主程序类,说明是一个springboot的应用程序
@SpringBootApplication
public class Application {
public static void main(String[] args) {
// SpringApplication.run--这个方法使spring启动起来
SpringApplication.run(Application.class, args);
}
}
3、编写相关的controller、service
//@ResponseBody
//@Controller
@RestController //作用:这个类的所有返回的数据直接写给浏览器,如果是对象,返回json格式
public class HelloWordController {
@RequestMapping("/hello")
public String hello(){
return "hello word 你好,世界!第一个springboot程序大功告成,yeah!!!";
}
}
4、运行主程序,在页面输入地址
比如:http://localhost:8080/hello
5、简化部署
<!--使用插件,把应用打成一个可执行的jar包-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.4.RELEASE</version>
</plugin>
</plugins>
</build>
将应用打成jar包,在cmd控制台使用java -jar demo.jar 的命令执行
二、探究helloworld
1、pom文件 启动器
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
spring-boot-starter web:可以看作场景启动器,帮助我们导入web模块正常运行所依赖的组件
SpringBoot将所有的场景功能抽取出来,做成一个个starters(启动器),只需要在项目里面引入这些starters相关的场景的所有依赖
2、主程序 (入口类)
@SpringBootApplication 标注一个主程序类,说明是一个springboot的应用程序
包含:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
//springboot的配置类,标注在哪个类上,说明此类是springboot的配置类 @Configuration:配置类上标注的这个注解
//配置类 代替 配置文件
@EnableAutoConfiguration //开启自动配置的功能
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
三、使用Spring Initializr快速创建spingboot
四、yml配置
1、@ConfigurationProperties 将类中和yml配置文件中的值绑定