spring-boot 项目 使用总结

spring-boot 项目 使用总结

1.创建一个maven 项目spring-boot-parent(parent),pom 设置项目类型为pom
2.创建一个模块spring initializr (java,maven,sdk17,jar,spring-web) boot-lesson1
3.在Application(main)方法同级包里创建一个java类:user.controller.UserController.java )
@RestController
public class UserController {
@GetMapping("/index")
public String index(){
return "hello world!";
}
}

4.在模块里pom.xml文件配置发布启动的主类mainClass



org.springframework.boot
spring-boot-maven-plugin

com.denny.bootlesson1.BootLesson1Application



5.运行测试http://localhost:8080/index
若端口被占用了在resource.application.properties文件添加端口号:
server.port=8088

6.用maven.lifecycle.package 工具执行发布,发布完成,在target/test-classes/boot-lesson1-0.0.1-SNAPSHOT.jar 生成了发布jar文件
7.复制boot-lesson1-0.0.1-SNAPSHOT.jar文件到需要发布的服务器(需先安装jdk)运行:java -jar boot-lesson1-0.0.1-SNAPSHOT.jar

8.配置对象,map可以和对象转换,将配置信息转化为javabear 实体类(application.yml-->config.java)
application.yml:
server:
port: 8888
servlet:
context-path: /test

自定义的配置key value

name1: "zhangsan \n zhansan"
name2: "lisi"

配置对象,map可以和对象转换,将配置信息转化为javabear

friends:
lastName: zhangsan
age: 20
pets:
- cat
- dog
- pig
conditional:
k1: v1
k2: v2

Friends.java:
package com.denny.bootlesson1.user.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
@ConfigurationProperties(prefix = "friends")
public class Friends {
private String lastName;

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

private int age;

public List<String> getPets() {
    return pets;
}

public void setPets(List<String> pets) {
    this.pets = pets;
}

@Override
public String toString() {
    return "Friends{" +
            "lastName='" + lastName + '\'' +
            ", age=" + age +
            ", pets=" + pets +
            '}';
}

private List<String> pets;

public Map<String, Object> getConditional() {
    return conditional;
}

public void setConditional(Map<String, Object> conditional) {
    this.conditional = conditional;
}

private Map<String, Object> conditional;

}

UserController.java
@RestController
public class UserController {

@Value("${name1:default}")
private String name1;

@Value("${name2:default}")
private String name2;

@GetMapping("/names")
public  String names(){
    System.out.println(name1);
    System.out.println(name2);
    return "ok";
}

@Autowired
private Friends friends;

@GetMapping("/map")
public  String map(){
    System.out.println(friends);
    return "friends";
}
posted @ 2023-06-17 23:54  大树2  阅读(27)  评论(0编辑  收藏  举报