下面列出了org.springframework.core.env.Environment#containsProperty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private boolean isSpringSecurityEnabled(ConditionContext ctx) {
boolean enabled = true;
Environment env = ctx.getEnvironment();
for (String propName : props) {
if (env.containsProperty(propName)) {
if (!Boolean.parseBoolean(env.getProperty(propName))) {
enabled = false;
break;
}
}
}
if (enabled) {
enabled = ClassUtils.isPresent(SPRING_SEC_CLASS_NAME, ctx.getClassLoader());
}
return enabled;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event)
{
Environment environment = event.getEnvironment();
final String loggingFile = environment.getProperty(PROP_LOGGING_FILE);
if (loggingFile != null)
{
System.setProperty(PROP_LOGGER, "FILE");
try
{
System.setProperty("logging.dir", new File(loggingFile).getParent());
}
catch (Exception ex)
{
System.err.println("Unable to set up logging.dir from logging.file " + loggingFile + ": " +
Throwables.getStackTraceAsString(ex));
}
}
if (environment.containsProperty("debug") &&
!"false".equalsIgnoreCase(environment.getProperty("debug", String.class)))
{
System.setProperty(PROP_SPRING_BOOT_LOG_LEVEL, "DEBUG");
}
setProccessId();
}
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
//获取环境
Environment env = context.getEnvironment();
//包含环境属性 magic 则返回true
return env.containsProperty("magic");
}
@Bean
public BrokerProperties brokerProperties(Environment env,
@Qualifier(ID_GENERATOR_BEAN_NAME) Supplier<BigInteger> idGenerator) {
BrokerProperties properties = new BrokerProperties();
// set default from env
if (env.containsProperty("spring.application.name")) {
properties.setId(env.getProperty("spring.application.name"));
}
properties.setRouteId(idGenerator.get());
return properties;
}
private void setDubboApplicationNameProperty(Environment environment, Map<String, Object> defaultProperties) {
String springApplicationName = environment.getProperty(SPRING_APPLICATION_NAME_PROPERTY);
if (StringUtils.hasLength(springApplicationName)
&& !environment.containsProperty(DUBBO_APPLICATION_NAME_PROPERTY)) {
defaultProperties.put(DUBBO_APPLICATION_NAME_PROPERTY, springApplicationName);
}
}
private Integer initPlatform(Environment environment, Platform platform) {
String propetyKey = ROOT_VOLUME_SIZE_PROPERTY_PREFIX + platform.value();
if (!environment.containsProperty(propetyKey)) {
LOGGER.debug("{} property is not set. Defaulting its value to 50.", propetyKey);
}
return Integer.valueOf(environment.getProperty(propetyKey, DEFAULT_ROOT_VOLUME_SIZE.toString()));
}
void configureTopology(Environment environment, ConnectionEndpointList connectionEndpoints,
int connectionCount) {
if (connectionCount < 1) {
if (!environment.containsProperty(SPRING_DATA_GEMFIRE_CACHE_CLIENT_REGION_SHORTCUT_PROPERTY)) {
System.setProperty(SPRING_DATA_GEMFIRE_CACHE_CLIENT_REGION_SHORTCUT_PROPERTY,
LOCAL_CLIENT_REGION_SHORTCUT.name());
}
}
}
private static boolean isSslConfigured(Environment environment) {
return (environment.containsProperty(SECURITY_SSL_KEYSTORE_PROPERTY)
&& environment.containsProperty(SECURITY_SSL_TRUSTSTORE_PROPERTY))
|| (environment.containsProperty(GEMFIRE_SSL_KEYSTORE_PROPERTY)
&& environment.containsProperty(GEMFIRE_SSL_TRUSTSTORE_PROPERTY));
}
private void configureAuthentication(Environment environment, VcapPropertySource vcapPropertySource,
CloudCacheService cloudCacheService, Properties cloudCacheProperties) {
if (isSecurityPropertiesNotSet(environment)) {
if (environment.containsProperty(SECURITY_USERNAME_PROPERTY)) {
String targetUsername = environment.getProperty(SECURITY_USERNAME_PROPERTY);
vcapPropertySource.findUserByName(cloudCacheService, targetUsername)
.flatMap(User::getPassword)
.map(password -> {
cloudCacheProperties.setProperty(SECURITY_USERNAME_PROPERTY, targetUsername);
cloudCacheProperties.setProperty(SECURITY_PASSWORD_PROPERTY, password);
return password;
})
.orElseThrow(() -> newIllegalStateException(
"No User with name [%s] was configured for Cloud Cache service [%s]",
targetUsername, cloudCacheService.getName()));
}
else {
vcapPropertySource.findFirstUserByRoleClusterOperator(cloudCacheService)
.ifPresent(user -> {
cloudCacheProperties.setProperty(SECURITY_USERNAME_PROPERTY, user.getName());
user.getPassword().ifPresent(password ->
cloudCacheProperties.setProperty(SECURITY_PASSWORD_PROPERTY, password));
});
}
}
}
@Bean
public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource , Environment environment) throws IOException{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean() ;
sqlSessionFactoryBean.setDataSource(dataSource);
//别名包
sqlSessionFactoryBean.setTypeAliasesPackage(environment.getRequiredProperty(PROPERTY_MYBATIS_ALIAS_PACKAGE));
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver() ;
//获取mybatis映射文件路径,classpath:mybatis/mybatis-config.xml
if(environment.containsProperty(PROPERTY_MYBATIS_CONFIG)){
sqlSessionFactoryBean.setConfigLocation(resolver.getResource(environment.getRequiredProperty(PROPERTY_MYBATIS_CONFIG)));
}
//获取mybatis映射文件路径,例:classpath*:com/framework/sample/mapper/*Mapper.xml
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(environment.getRequiredProperty(PROPERTY_MYBATIS_MAPPER_LOCATION)));
//开启后将在启动时检查设定的parameterMap,resultMap是否存在,是否合法
sqlSessionFactoryBean.setFailFast(true) ;
//存储mybatis的插件
List<Interceptor> interceptorList = new ArrayList<Interceptor>() ;
//初始化mybatis的插件
initPlugins(interceptorList , environment) ;
//设置mybatis插件
sqlSessionFactoryBean.setPlugins(interceptorList.toArray(new Interceptor[]{}));
//创建自定义的的Configuration
Configuration configuration = new Configuration() ;
//设置ObjectWrapperFactory,在其中映射mybatis查询结果和jpa实体
configuration.setObjectWrapperFactory(new JPAObjectWrapperFactory());
sqlSessionFactoryBean.setConfiguration(configuration);
return sqlSessionFactoryBean ;
}
@Override
public boolean containsProperty(String key) {
Environment environment = getEnvironment();
if (environment != null) {
return environment.containsProperty(key);
}
return false;
}
protected RegistryStrategiesProvider doCreate(ConfigurableListableBeanFactory beanFactory) {
final Environment environment = beanFactory.getBean(Environment.class);
if (environment.containsProperty(SERVICE_DISCOVERY_ZK_HOST)) {
return new ZookeeperRegistryBeanProvider(beanFactory);
} else if (environment.containsProperty(SERVICE_DISCOVERY_ADDRESS)) {
return new InMemoryRegistryBeanProviderFactory(beanFactory);
}
throw new IllegalStateException(String.format("Provide one of props with registry either %s or %s",
SERVICE_DISCOVERY_ZK_HOST, SERVICE_DISCOVERY_ADDRESS));
}
private String initPlatform(Environment environment, Platform platform) {
String propetyKey = DEFAULT_INSTANCE_TYPE_PROPERTY_PERFIX + platform.value();
if (!environment.containsProperty(propetyKey)) {
LOGGER.debug("{} property is not set. Defaulting its value to empty string.", propetyKey);
}
return environment.getProperty(propetyKey, "");
}
private boolean nodeExistsAtIndex(Environment environment, int index) {
return environment.containsProperty(buildNodeAttribute(NODE_NAME_ATTRIBUTE, index));
}
/**
* @param registryAlias
* @return
* @throws SofaBootRpcRuntimeException
*/
public RegistryConfig getRegistryConfig(String registryAlias) throws SofaBootRpcRuntimeException {
RegistryConfig registryConfig;
String registryProtocol;
String registryAddress;
String currentDefaultAlias;
if (StringUtils.isNotBlank(customDefaultRegistry)) {
currentDefaultAlias = customDefaultRegistry;
} else {
currentDefaultAlias = DEFAULT_REGISTRY;
}
if (StringUtils.isEmpty(registryAlias)) {
registryAlias = currentDefaultAlias;
}
//cloud be mesh,default,zk
if (registryConfigs.get(registryAlias) != null) {
return registryConfigs.get(registryAlias);
}
// just for new address
if (DEFAULT_REGISTRY.equalsIgnoreCase(registryAlias)) {
registryAddress = sofaBootRpcProperties.getRegistryAddress();
} else if (registryAlias.equals(customDefaultRegistry)) {
registryAddress = customDefaultRegistryAddress;
} else {
registryAddress = sofaBootRpcProperties.getRegistries().get(registryAlias);
}
//for worst condition.
if (StringUtils.isBlank(registryAddress)) {
registryProtocol = SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL;
} else {
final int endIndex = registryAddress.indexOf("://");
if (endIndex != -1) {
registryProtocol = registryAddress.substring(0, endIndex);
} else {
registryProtocol = registryAlias;
}
}
if (registryConfigMap.get(registryProtocol) != null) {
RegistryConfigureProcessor registryConfigureProcessor = registryConfigMap.get(registryProtocol);
registryConfig = registryConfigureProcessor.buildFromAddress(registryAddress);
registryConfigs.put(registryAlias, registryConfig);
//不再处理以.分隔的.
final Environment environment = sofaBootRpcProperties.getEnvironment();
if (environment.containsProperty(SofaOptions.CONFIG_RPC_REGISTER_REGISTRY_IGNORE)) {
if (Boolean.TRUE.toString().equalsIgnoreCase(
environment.getProperty(SofaOptions.CONFIG_RPC_REGISTER_REGISTRY_IGNORE))) {
registryConfig.setRegister(false);
}
}
return registryConfig;
} else {
throw new SofaBootRpcRuntimeException("registry config [" + registryAddress + "] is not supported");
}
}
@Override
public boolean isCloudPlatform(Environment environment) {
return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES");
}
private static String resolveTrustedKeystoreName(Environment environment) {
return environment != null && environment.containsProperty(TRUSTED_KEYSTORE_FILENAME_PROPERTY)
? environment.getProperty(TRUSTED_KEYSTORE_FILENAME_PROPERTY)
: TRUSTED_KEYSTORE_FILENAME;
}
/**
* 构建alibaba的数据库连接池
* @param environment
* @param propertyPrefix
* @return
*/
@Override
public DataSource buildDataSource(Environment environment , String propertyPrefix){
DruidDataSource dataSource = new DruidDataSource() ;
dataSource.setDriverClassName(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_DRIVER));
dataSource.setUrl(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_URL));
dataSource.setUsername(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_USERNAME));
dataSource.setPassword(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_JDBC_PASSWORD));
//分别设置最大和最小连接数
if(environment.containsProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MAXACTIVE)){
dataSource.setMaxActive(environment.getProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MAXACTIVE , Integer.class));
}
if(environment.containsProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MINIDLE)){
dataSource.setMinIdle(environment.getProperty(propertyPrefix+PROPERTY_NAME_JDBC_POOL_MINIDLE , Integer.class));
}
dataSource.setDefaultAutoCommit(false);
//是否需要进行验证
dataSource.setValidationQuery(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_QUERY));
//由连接池中获取连接时,需要进行验证
dataSource.setTestOnBorrow(true) ;
//归还连接时不需要验证
dataSource.setTestOnReturn(false) ;
//连接空闲时进行验证
dataSource.setTestWhileIdle(true) ;
//设置datasource监控,只对sql执行状态进行监控
try {
dataSource.setFilters("stat") ;
}catch (Exception e){
e.printStackTrace() ;
}
if(StringUtils.isNotBlank(environment.getProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL))){
//连接有效的验证时间间隔
dataSource.setValidationQueryTimeout(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL , Integer.class));
//连接空闲验证的时间间隔
dataSource.setTimeBetweenEvictionRunsMillis(environment.getRequiredProperty(propertyPrefix+PROPERTY_NAME_VALIDATION_INTERVAL , Long.class));
}
return dataSource ;
}
@Override
public boolean isCloudPlatform(Environment environment) {
return environment.containsProperty("VCAP_APPLICATION") || environment.containsProperty("VCAP_SERVICES");
}
private boolean isSecurityPropertiesSet(Environment environment) {
boolean securityPropertiesSet = environment.containsProperty(SECURITY_USERNAME_PROPERTY)
&& environment.containsProperty(SECURITY_PASSWORD_PROPERTY);
logger.debug("Security Properties set? [{}]", securityPropertiesSet);
return securityPropertiesSet;
}