总:Environment接口用法

接口简介

此接口表示了当前应用运行在哪个环境下。典型代表了应用环境的两个方面:profilesproperties。与属性相关的属性通过父接口PropertyResolver暴露。

一个profile是一个命名的,逻辑的bean定义的组仅当指定的profile激活是才在容器中注册。Beans可以赋予一个profile值无论在XML或注解定义;参阅spring-beans 3.1约束或org.springframework.context.annotation.Profile注解获取更详细的语法。Environment对象与profiles相关的角色是发现哪个profiles 是当前激活的通过getActiveProfiles,哪个profiles应该是默认的getDefaultProfiles

Properties在大多数应用中办演了重要的角色,可以从各种各样的源中获取:属性文件,JVM系统属性,系统环境变量,JNDI,servlet环境参数,ad-hoc Properties对象,映射等。environment对象与properties办演的角色是提供一个方便的服务接口来配制属性源和从这些属性文件中解析他们。

ApplicationContext管理的bean可以注册EnvironmentAware@Inject``Enviornment用于查询profile状态或直接解析属性。

大多数情况下,然而,应用级别的bean不用直接使用Environemnt而是使用PropertySourcesPlaceholderConfigurer,其自己是一个EnvironmentAware,在Spring 3.1 当使用<context:property-placeholder/>时默认注册

environment对象一定要通过ConfigurableEnvironemnt接口配制,并由AbstractApplicationContext子类的getEnvironemnt()方法返回。参阅ConfigurableEnvironment来获取在应用环境refresh()之前的property sources的操纵示例

方法简介

String[] getActiveProfiles();

返回此环境下显示激活的profiles集合。Profiles用于有条件的创建一组逻辑上的bean定义,例如基于总署的环境。Profiles可以通过 设置"spring.profiles.active"系统属性激活,或调用ConfigurableEnvironment.setActiveProfiles。如果没有profiles显示的被激活,然后任何getDefaultProfiles()获取的默认profiles将会自动被激活。

String[] getDefaultProfiles();

当没有显示的设置激活的profiles时,返回默认的profiles

boolean acceptsProfiles(String... profiles);

返回一个或多个指定的profiles是否被激活,如果没有显示激活profiles,是否一个或多个指定的profiles被包括在默认的profiles。如果一个profile以'!'那么逻辑是相反的,i.e. 方法将会返回true如果指定的profile没有被激活。例如env.accetpsProfiles("p1", "!p2")将会返回true如果profile p1是激活的或p2没有被激活。

如果没指定参数或任何的一个profile是null, 空 或空白的将会抛出IllegalArgumentException

results matching ""

    No results matching ""