@Value("${配置文件中的key:默认值}") @Value("${配置文件中的key}")
方法1:使用的类文件中定义变量,直接使用变量
import org.springframework.beans.factory.annotation.Value; @Value("${baseProperties.factory}") private String sysFactory; @Value("${baseProperties.factory-name}") private Boolean sysFactoryName; public ResponseData test() { System.out.println(sysFactory +";"+sysFactoryName); return new SuccessResponseData(); }
方法2:定义在常量类中
代码未实现
注意:需要把配置类文件添加进去才可以生效; set和get方法需要保留;Controller类文件读取null,但Service实现类可以取值;
@Configuration
@EnableConfigurationProperties(BaseProperties.class)
@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; } }
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(); }