@ConfigurationProperties
该注解是加载配置文件中的参数,里面有个属性Prefix是前缀,只要标注该注解的类里对应的成员变量与配置文件中参数与之对应即可获取参数,注意: 这里必须要有Setter方法,否则无法获取参数变量会报错哦,还有该类必须是在Spring容器注册的类,标注@Component。
server:
port: 8086
person:
name: 唰唰黎
age: 12
@Component
@ConfigurationProperties(prefix = "person")
public class PersonConfig {
private String name;
private Integer age;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
}
@Value
它的属性支持Spel语法,在成员变量标注改注解,在注解的属性value写上对应的Spel语法,该类也必须是在Spring容器注册的类,标注@Component。
server:
port: 8086
person:
name: 唰唰黎
age: 12
mytest:
name: test
@Component
public class PersonConfig {
@Value("${mytest.name}")
private String testName;
public String getTestName() {
return testName;
}
}
@PropertySource
加载指定的properties配置文件,只能加载porperties文件
创建一个mytest.properties文件
animal.name=龙域
animal.age=24
my.test=我是测试
@PropertySource("classpath:mytest.properties")
@Component
@ConfigurationProperties(prefix = "animal")
public class PersonConfig2 {
private String name;
private Integer age;
@Value("${my.test}")
private String testName;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public String getTestName() {
return testName;
}
}
在这你有可能出现获取参数乱码,因为porperties默认是ASCII码,中间有转码过程,使用IDEA的小伙伴可以这样解决,打开File -> Setting,搜索file encodings (注意红标处)
点击OK ,如果你已经创建了porperties文件,把他删掉重新创建一个,这下就不会乱码了
@ImportResource
加载指定的Spring配置文件
这个只需了解有这种用法,不需要掌握,因为SpringBoot不建议这种Bean配置
创建BeanClass类
public class BeanClass {
public void hello(){
System.out.println("hello i am BeanClass");
}
}
创建mybean.xml的Spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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="beanClass" class="com.example.myspringboot.config.BeanClass" />
</beans>
测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyspringbootApplication.class)
public class ParentTest {
@Autowired
private BeanClass beanClass;
@Test
public void test1(){
beanClass.hello();
}
}