SpringBoot获取配置信息的三种方式总结
更新时间:2024年01月16日 10:16:53 作者:秋日的晚霞
这篇文章给大家介绍了SpringBoot获取配置信息的三种方式,@Value属性值注入,绑定配置类和通过 environment获取这三种方式,文中通过代码示例给大家介绍的非常详细,具有一定的参考价值,需要的朋友可以参考下
Spring获取配置信息的三种方式
1. @Value属性值注入
@Value("${student.name}")
private String name;
public static void main(String[] args) {
SpringApplication.run(SpringConfigDemoApplication.class, args);
}
@PostConstruct
private void init()
{
System.out.println("name = " + name);
}
2. 绑定配置类
@ConfigurationProperties(prefix = "student")
public class StudentProperties {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@EnableConfigurationProperties(StudentProperties.class)
@SpringBootApplication
public class SpringConfigDemoApplication {
@Value("${student.name}")
private String name;
@Autowired
private StudentProperties studentProperties;
public static void main(String[] args) {
SpringApplication.run(SpringConfigDemoApplication.class, args);
}
@PostConstruct
private void init()
{
System.out.println("name1 = " + name);
}
@PostConstruct
private void init2()
{
System.out.println("name2 = " +studentProperties.getName());
}
}
3. 通过 environment 获取
package com.sz.springconfigdemo;
import com.sz.springconfigdemo.properties.StudentProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import javax.annotation.PostConstruct;
@EnableConfigurationProperties(StudentProperties.class)
@SpringBootApplication
public class SpringConfigDemoApplication {
@Value("${student.name}")
private String name;
@Autowired
private StudentProperties studentProperties;
@Autowired
private Environment environment;
public static void main(String[] args) {
SpringApplication.run(SpringConfigDemoApplication.class, args);
}
@PostConstruct
private void init()
{
System.out.println("name1 = " + name);
}
@PostConstruct
private void init2()
{
System.out.println("name2 = " +studentProperties.getName());
}
@PostConstruct
private void init3()
{
String environmentProperty = environment.getProperty("student.name");
System.out.println("name3 = " +environmentProperty);
}
}
以上就是SpringBoot获取配置信息的三种方式总结的详细内容,更多关于SpringBoot获取配置信息的资料请关注脚本之家其它相关文章!
相关文章
Hibernate+JDBC实现批量插入、更新及删除的方法详解
这篇文章主要介绍了Hibernate+JDBC实现批量插入、更新及删除的方法,结合实例形式较为详细的分析了Hibernate与JDBC针对数据库的批量操作相关实现技巧,需要的朋友可以参考下2017-11-11
Mybatis Plus LambdaQueryWrapper的具体用法
Mybatis Plus 在其基础上扩展了 LambdaQueryWrapper,LambdaQueryWrapper 提供了更加简便的查询语法,同时也避免了SQL注入的风险,感兴趣的可以了解一下2023-11-11
解决logback-classic 使用testCompile的打包问题
这篇文章主要介绍了解决logback-classic 使用testCompile的打包问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07


最新评论