JAVA获取application.yml配置文件的属性值
application.yml配置参数
方式一:使用@Value方式(常用)
语法
@Value("${配置文件中的key:默认值}")
@Value("${配置文件中的key}")
方法1:使用的类文件中定义变量,直接使用变量
import org.springframework.beans.factory.annotation.Value; @Value("${baseProperties.factory}") private String sysFactory; @Value("${baseProperties.factory-name}") private String sysFactoryName; public ResponseData test() { System.out.println(sysFactory +";"+sysFactoryName); return new SuccessResponseData(); }
方法2:定义在配置类中,通过引入ApplicationConfig的对象读取数据
import com.holly.api.base.pojo.vo.ApplicationVO; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ApplicationConfig { @Value("${baseProperties.factory}") private String factory; @Value("${baseProperties.factory-name}") private String factoryName; @Bean public ApplicationVO getFactoryInfo() { ApplicationVO vo = new ApplicationVO(); vo.setFactory(factory); vo.setFactoryName(factoryName); return vo; } }
方式二:使用@ConfigurationProperties方式
注意:
1、需要把配置类文件添加进去才可以引入;
@Configuration
2、set和get方法需要保留,set方法不加static
3、Controller类文件读取null,但Service实现类可以取值;(原因不知道)
@Configuration
@ConfigurationProperties(prefix = "baseProperties")
public class BaseProperties { private static String factory; private static String factoryName; public static String getFactory() { return factory; } public void setFactory(String factory) { BaseProperties.factory = factory; } public static String getFactoryName() { return factoryName; } public void setFactoryName(String factoryName) { BaseProperties.factoryName = factoryName; } }
方式三:使用Environment方式
import org.springframework.core.env.Environment;
@Autowired
private Environment environment;
public ResponseData test() { System.out.println("env:" + environment.getProperty("baseProperties.factory")); System.out.println("env:" + environment.getProperty("baseProperties.factory-name")); return new SuccessResponseData(); }