@ProtertySource Environment类

@ProtertySource

@PropertySouce是spring3.1开始引入的基于java config的注解。

通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。

@Configuration

@ProtertySource("classpath:/com/soundsystem/app.properties")

public  class  ExpressiveConfig{

   @Autowired

   Environment   ent;

   @Bean

 public   BlankDisc  disc(){

    return   new BlankDisc(

      env.getPropert("disc.title"),

       env.getProperty("disc.artist"));

}

}

app.properties的文件内容:

disc.title=this is title value

disc.artist= this is artist value

这个属性文件会加载到Spring的Environment中。然后通过它的getProperty()方法来获取。

Environment

public String getProperty(String key)
public String getProperty(String key, String defaultValue)
<T> T getProperty(String key, Class<T> targetType);
<T> T getProperty(String key, Class<T> targetType, T defaultValue);

前两种形式的getProperty()方法会返回String类型的值,第二种如果没有获取到值,则会使用默认值

第三四中会返回对象,如我们需要Integer类型,如果得到String类型的值,还需要转换为Integer类型

int  count = env.getProperty("jdbc.connection.count",Integer.class ,30);//获取数据库连接池最大连接数,默认30

Environment还提供了几个与属性相关的方法。

getRequiredProperty();

如果使用getProperty时没有指定默认值,并且这个属性值没有定义的话,则会返回null,如果你希望定义这个属性值,那么可以使用getRequiredProperty()方法,如下
env.getRequiredProperty("disc.title"); 

这里如果没有定义该属性的话,会抛出IllegalStateException异常。

containsProperty();

如果检查是否存在,可以调用containsProperty()方法

boolean titleExists = env.containsProperty("disc.title");

getPropertyAsClass()

如果想将属性解析为类的话,使用getPropertyAsClass()方法

Class<CompactDisc>  cdClass = env.getPropertyAsClass("disc.class",CompactDisc.class);

Environment还提供了一些方法来检查哪些profile处于激活状态

String[] getActiveProfiles();  返回激活profile名称数值
String[] getDefaultProfiles(); 返回默认profile名称数值
boolean acceptsProfiles(String... profiles);  如果Environment支持给定profile的话,就返回true

猜你喜欢

转载自blog.csdn.net/m0_37668842/article/details/82756938