方式一: //创建Properties对象 Properties prop = new Properties(); //读取classPath中的properties文件 prop.load(ConsumerController.class.getClassLoader().getResourceAsStream("bean.properties")); //根据键取出值 String className = prop.getProperty("test");//读取bean.properties里面,test的值
==================================================================
方式二:
使用工具类,将属性@Value("server.port)类似赋值,类加@Component以服务注入,获取内容时,只需要@Autowired服务工具类,调用属性
@Component @Data public class Student { @Value("${server.port}") private String port; }
@Autowired private Student student; 使用时直接注入,然后调用属性值
===================================================================
方式三:
引入依赖
<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; }调用方式不在描述,依赖注入直接调用
来源:CSDN
作者:励志重写JDK
链接:https://blog.csdn.net/ajax_yan/article/details/104778701