SpringBoot有哪几种方式获取application.properties中的值呢?
下文笔者讲述SpringBoot获取application.properties中的值的方法分享,如下所示:
通过上下文environment环境变量获取属性值
@SpringBootApplication public class SpringBoot01Application { public static void main(String[] args) { ConfigurableApplicationContext context=SpringApplication.run(SpringBoot01Application.class, args); String str1=context.getEnvironment().getProperty("username"); System.out.println(str1); } }
自动装配到指定Bean
这个也是借助于environmentimport org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class User { @Autowired private Environment env; public void getUserName() { System.out.println("==========" + env.getProperty("username")); } }
使用@Value注解
package com.java265; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @PropertySource("classpath:jdbc.properties") public class Jdbc { @Value("${jdbc.user}") private String user; @Value("${jdbc.password}") private String password; public void speack(){ System.out.println("username:"+user+"------"+"password:"+password); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。