前言:最近在复习springboot的相关知识,所以在这里记录一下方便自己以后复习。
标注了这个注解的类,告诉springboot,所有的相关属性,都与配置文件里设置的属性进行绑定。用@ConfigurationProperties
中可以设置prefix = "xxxx"
前缀来标识。
student:
name: jack
age: 18
weight: 180
lists: [1,2,3,4,5]
maps: {k1: v1,k2: v2,k3: v3}
//部分代码,省去了get set与toostring方法
@Component
@ConfigurationProperties(prefix = "student")
public class Student {
private String name;
private Integer age;
private Integer weight;
private List<String> lists;
private Map<String,String>maps;
进行测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringboothelloworldApplicationTests {
@Autowired
private Student student;
@Test
public void contextLoads() {
System.out.println(student);
}
}
加载指定的配置文件,SpringBoot
默认加载的是application.properties
那么也就是说我们所有的配置信息都要放在这个文件里面,如果我们想指定加载配置文件,就可以通过@PropertySource
代码如下:
配置了一个student.properties
student.name=jack
student.age=18
student.weight=170
student.lists=1,2,3,4
student.maps.k1=v1
student.maps.k2 =v2
指定加载student.properties
,通过配置@PropertySource(value = {"classpath:student.properties"})
@Component
@PropertySource(value = {"classpath:student.properties"})
@ConfigurationProperties(prefix = "student")
public class Student {
private String name;
private Integer age;
private Integer weight;
private List<String> lists;
private Map<String,String>maps;
同样进行测试打印输出结果如下:
可以看到student.properties
配置的内容被成功加载。
因为SpringBoot
是没有配置文件的,如果我想让我们编写的Spring
配置文件生效,如beans.xml
,就可以使用@ImportResource
注解,将配置文件导入进来。
首先先编写一个beans.xml
,设置Student
基本的属性
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="StudentByxml" class="com.kuake.springbootHelloworld.entity.Student">
<property name="name" value="jack">property>
<property name="age" value="18">property>
<property name="weight" value="175">property>
<property name="lists">
<list>
<value>1value>
<value>11value>
<value>1111value>
list>
property>
<property name="maps">
<props>
<prop key="KK1">VV1prop>
<prop key="KK2">VV2prop>
<prop key="KK3">VV3prop>
props>
property>
bean>
beans>
编写测试方法:
@Resource(name = "StudentByxml")
private Student studentByxml;
@Test
public void contextLoads() {
System.out.println(studentByxml);
}
看一下控制台输出结果:
可以看到学生的信息,就是我们在beans.xml
当中配置的信息,说明配置文件被成功加载。
xxxx.properties
文件spring.xml
的配置文件