spring中配置文件的属性注入都是@Value("${}")这种,springboot中提供了另一种(可以说是简化吧)。
1.pom.xml中引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
亲测:不引入也可(可能是其他依赖包中已引入)
2.application.properties中编写配置:
mytest.name=haha
mytest.password=123456
mytest.age=26
3.配置文件的属性注入类:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @description:
* @author:
* @create: 2019-02-12 09:54
**/
@Component
@ConfigurationProperties(prefix = "mytest")//prefix指定了配置文件属性的前缀为mytest,并且按照属性名进行自动匹配,例如:mytest.name属性值会自动setter到private String name域中。
public class EntityTest {
private String name;
private String password;
private Integer age;
@Override
public String toString() {
return "EntityTest{" +
"name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
注意:setter方法是必须的!
4.启动类测试:
@org.springframework.boot.autoconfigure.SpringBootApplication//@EnableAutoConfiguration @ComponentScan
public class SpringBootApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
@Autowired
EntityTest entityTest;
@Override
public void run(String... args) throws Exception {
System.out.println(entityTest);
}
}
运行结果:EntityTest{name='haha', password='123456', age=26}