美文网首页
SpringBoot

SpringBoot

作者: 月如钩dgf | 来源:发表于2021-05-06 23:10 被阅读0次

springBoot问题积累持续。。。

问题一:

junit注解使用@Before不生效问题,初始化初始参数失败问题
原因:junit使用4.13.2版本使用@Before不行,可以使用@BeforeEach

问题二:

用浏览器发送post请求
Google浏览器,F12,进入Console
// 按住shfit+Enter,可以下一行继续,不要直接Enter

var send = new XMLHttpRequest();
send .open("POST", "http://localhost:9001/actuator/shutdown", true);
send .send();

重点:

1.SpringBoot服务必要配置

pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

启动类:在工程代码的主目录下,其中@SpringBootApplication注解包含了@SpringBootConfiguration,@EnableAuto-Configuration和@ComponentScan,开启了包括扫描,配置和自动配置的功能。

@SpringBootApplication
public class SpringdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringdemoApplication.class, args);
    }

}

2.SpringBoot编写测试用例简单demo

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SpringdemoApplicationTests {
 @LocalServerPort //启动springBoot会随机生成一个端口号
 private  int port;
 private URL base;
 @Autowired
 private TestRestTemplate template; //测试类

 @BeforeEach
 public void setUp() throws Exception{
     this.base = new URL("http://localhost:" + port + "/hello");
 }
 
   @Test
    public void getHello(){
       ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
       assertThat(response.getBody(), equalTo("hello springBoot"));
   }
}

3.SpringBoot配置文件

自定义属性
application.yml

my:
  name: liming
  age: 14
  number: ${random.int}
  uuid: ${random.uuid}
  max: ${random.int(10)}
  value: ${random.value}
  greeting: hi, i'm ${my.name}
management:
      endpoints:
        web:
          exposure:
            include: "*"
      endpoint:
        health:
          show-details: always
        shutdown:
          enabled: true
      server:
        port: 9001

读取配置文件application.yml的属性值在变量上加@Value("${属性名}")
自定义配置文件读取test.properties

com.test.name=liming
com.test.age=15

代码中赋值给javaBean
@Configuration
@PropertySource(value = "classpath:test.properties")
@ConfigurationProperties(prefix = "com.test")
public class User {

    private  String name;
    private int age;
    //省略 ......

相关文章

网友评论

      本文标题:SpringBoot

      本文链接:https://www.haomeiwen.com/subject/vlyjdltx.html