1.常见文件格式
xml,properties,json,yml
YAML(Yet Another Markup Language)
写
YAML
要⽐写
XML
快得多
(
⽆需关注标签或引号
)
使⽤空格
Space
缩进表示分层,不同层次
之间的缩进可以使⽤不同的空格数⽬
注意:
key
后⾯的冒号,后⾯⼀定要跟⼀个空格
,
树状结构
Springboot
⾥⾯常⽤
xx.properties
(推荐)
Key=Value
格式
语法简单,不容易出错
2.注解配置⽂件映射属性和实体类
配置文件加载
方式1
1.Controller上⾯配置 @PropertySource({"classpath:resource.properties"})
2.增加属性 @Value("${test.name}")//test.name配置文件里的key
private String name;
方式2 实体类配置⽂件
1
、添加
@Component
注解;
2
、使⽤
@PropertySource
注解指定配置⽂件位置;
3
、使⽤
@ConfifigurationProperties
注解,设置相关属性;
4
、必须 通过注⼊
IOC
对象
Resource
进来 , 才能在类中使⽤获取的配置⽂件值。
@Configuration
@ConfigurationProperties(prefix="test")
@PropertySource(value="classpath:test.properties")
public class Test{
}
常⻅问题:
1
、配置⽂件注⼊失败,Could not resolve placeholder
解决:根据springboot
启动流程,会有⾃动扫描包没有扫描到相关注解, 默认
Spring
框架实现会从声明
@ComponentScan
所在的类的
package进⾏扫描,来⾃动注⼊, 因此启动类最好放在根路径下⾯,或者指定扫描包范围
spring-boot
扫描启动类对应的⽬录和⼦⽬录
2
、注⼊
bean
的⽅式,属性名称和配置⽂件⾥⾯的
key
⼀⼀对应,就⽤加
@Value
这个注解
如果不⼀样,就要加
@value("${XXX}")
@Value("${test.test}")
private String test;
3 单元测试
引⼊依赖
<!--springboot程序测试依赖,如果是⾃动创建项⽬默认添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency
配置注解
@RunWith(SpringRunner.class) //底层⽤junit SpringJUnit4ClassRunner
@SpringBootTest(classes={AppMain.class})//启动整个springboot⼯程
public class SpringBootTests { }
常⽤单元测试的注解
@Before、@Test、@After
断⾔
判断程序结果是否符合预期
TestCase.assertXXX。
Controller层登录⽅法测试
@Autowired
private TestController testController;
@Test
public void loginTest(){
User user = new User();
user.setUsername("test");
user.setPwd("1234");
int relCode = userController.login(user);
TestCase.assertEquals(0,relCode );
}
表Service层单元测试
@Autowired
private TestService testService;
@Test
public void testList(){
List<User> userList = testService.listUser();
TestCase.assertTrue(userList.size()>0);
}
MockMvc调⽤Controller层API接⼝
测试
Controller
对外提供的接⼝
增加类注解
@AutoConfifigureMockMvc
注⼊⼀个
MockMvc
类
API
:
perform
执⾏⼀个
RequestBuilder
请求
andExpect
:添加
ResultMatcher->MockMvcResultMatchers
验证规则
andReturn
:最后返回相应的
MvcResult->Response
@Autowired
private MockMvc mockMvc;
@Test
public void testVideoListApi()throws Exception
{
MvcResult mvcResult =
mockMvc.perform(MockMvcRequestBuilders.get("/api/pub/test/list"))
.andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
int status = mvcResult.getResponse().getStatus();
System.out.println(status);
//String result = mvcResult.getResponse().getContentAsString();
String result = mvcResult.getResponse().getContentAsString(Charset.forName("utf-8"));
System.out.println(result);
}