springboot的application.properties文件中可以定义一些可配置的常量。在程序中我们不需要再重新的读取文件,我们可以直接使用@Value注解读取配置文件中的值。
首先看一下配置文件
application.properties中的内容是:
spring.profiles.active=dev
application-dev.properties文件的内容是:
server.port=9991 spring.datasource.url=jdbc:mysql://localhost:3306/xytest spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver democonfig.name=dev democonfig.age=122
为了读取democonfig.name和democonfig.age的值,我们可以新建一个类,专门读取配置文件。
@Component public class DemoConfig { @Value("${democonfig.name}") public String name; @Value("${democonfig.age}") public int age; }
这样之后,每次实例化的类中name的值就是dev age的值就是122。
这样就完成了我们的目的。在类中直接读取了配置文件中的信息。