从配置文件properties中获取配置的三种方式

从配置文件properties中获取配置的三种方式

@RestController
@RequestMapping(value = "/api/test")
public class TestConfigController {
	//第一种
    @Autowired
    Environment environment;
	//第二种
    @Value("${pay.alipay.url}")
    private String alipayUrl;

	//第三种
    @Autowired
    ConfigrationBean configrationBean;
    
    @RequestMapping(value="/test1",method = RequestMethod.GET)
    public void test(){

        System.out.println("通过Env对象获取:"+environment.getProperty("pay.alipay.url"));
        System.out.println("通过@Value注解获取配置信息:"+alipayUrl);

        System.out.println("通过springboot注解获取配置信息:"+configrationBean.getAlipay().toString());
        System.out.println("通过springboot注解获取配置信息:"+configrationBean.getWeixin().toString());

    }
}

第三种获取配置信息是通过springboot特性将配置信息在spring容器初始化的时候读取到pojo中。优点是不用通过@value把每个配置信息都读取出来,比较简洁。

@Component
@PropertySource("classpath:configprops.properties")
@ConfigurationProperties(prefix="pay")
public class ConfigrationBean {
    private final HashMap alipay = Maps.newHashMap();
    private final HashMap weixin = Maps.newHashMap();
    public HashMap getAlipay(){return alipay;};
    public HashMap getWeixin(){return weixin;};
}

你可能感兴趣的:(spring,配置文件的读取方式)