方式一:
//创建Properties对象
Properties prop = new Properties();
//读取classPath中的properties文件
prop.load(ConsumerController.class.getClassLoader().getResourceAsStream("bean.properties"));
//根据键取出值
String className = prop.getProperty("test");//读取bean.properties里面,test的值
==================================================================
Second way:
When using the tools, the property @Value ( "server.port) similar assignments, class of service plus @Component injection, access to content, just @Autowired service tool
Class, call the property
@Component
@Data
public class Student {
@Value("${server.port}")
private String port;
}
@Autowired
private Student student; 使用时直接注入,然后调用属性值
private static String port; // If the property is static, you can use method injection @Value("${server.port}") public void setPort(Integer port) { Student.port= port; }
===================================================================
Three ways:
The introduction of dependence
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
<version>2.2.5.RELEASE</version>
</dependency>
@Component//不加无法注入
@Data//插件lombok帮助省略getset
@EnableConfigurationProperties(Student.class)
@ConfigurationProperties(prefix = "spring.activemq", ignoreUnknownFields = true)//加上注解提示有问题(提示没有经过EnableConfigurationProperties...spring的组件,你懂了,要加上EnableConfigurationProperties这个注解,才能成为spring组件)
public class Student {
private String brokerUrl;
}调用方式不在描述,依赖注入直接调用