Spring中的Environment

用来表示整个应用运行时的环境,为了更形象地理解Environment,你可以把Spring应用的运行时简单地想象成两个部分:一个是Spring应用本身,一个是Spring应用所处的环境,而Environment这个接口,就是对这个所处的环境的概念性建模。

Environment在容器中是一个抽象的集合,是指应用环境的2个方面:profiles和properties。

Profile

profile配置是一个被命名的、bean定义的逻辑组,这些bean只有在给定的profile配置激活时才会注册到容器。不管是XML还是注解,Beans都有可能指派给profile配置。Environment环境对象的作用,对于profiles配置来说,它能决定当前激活的是哪个profile配置,和哪个profile是默认。

 

  • 一个profile就是一组Bean定义的逻辑分组。
  • 这个分组,也就 这个profile,被赋予一个命名,就是这个profile名字。
  • 只有当一个profile处于active状态时,它对应的逻辑上组织在一起的这些Bean定义才会被注册到容器中。
  • Bean添加到profile可以通过XML定义方式或才annotation注解方式。
  • Environment对于profile所扮演的角色是用来指定哪些profile是当前活跃的缺省。

Properties

properties属性可能来源于properties文件、JVM properties、system环境变量、JNDI、servlet context parameters上下文参数、专门的properties对象,Maps等等。Environment对象的作用,对于properties来说,是提供给用户方便的服务接口、方便撰写配置、方便解析配置。

 

  • 配置属性源。
  • 从属性源中获取属性。

容器(ApplicationContext)所管理的bean如果想直接使用Environment对象访问profile状态或者获取属性,可以有两种方式

(1)实现EnvironmentAware接口。

(2)@Inject或者@Autowired一个Environment对象。

绝大数情况下,bean都不需要直接访问Environment对象,而是通过类似@Value注解的方式把属性值注入进来。

原文地址:https://blog.csdn.net/CHS007chs/article/details/80606498

 

@PropertySource(value = { “classpath:application.properties” })注解可以让在application.properties文件中定义的属性对Spring Envirronment bean可用,Environment接口提供了getter方法读取单独的属性值。

@PropertySources(value = {@PropertySource("classpath:/runtime.properties")})
@Component("propertyConfig")
public class PropertyConfig implements IPropertyConfig{

    @Resource
    Environment env;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    public String getProperty(String key) {
        if (null == key) {
            return null;
        }
        if (env.getProperty(key) == null) {
            return null;
        }
        try {
            return new String(env.getProperty(key).getBytes("iso-8859-1"),"utf-8");
        } catch (UnsupportedEncodingException e) {
            return env.getProperty(key);
        }
    }
}

 

posted @ 2018-07-03 14:44  三尺墨  阅读(120)  评论(0)    收藏  举报