1. 程式人生 > >非託管類獲取Spring容器資訊

非託管類獲取Spring容器資訊

非託管類: 不受Spring容器管理的類;

獲取bean

@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String beanId) {
        return applicationContext.getBean(beanId);
    }
}

獲取配置

@Component
public class PropertiesUtils implements EmbeddedValueResolverAware {
    private static StringValueResolver valueResolver;

    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        PropertiesUtils.valueResolver = stringValueResolver;
    }

    public static String getPropertiesValue(String key) {
        return valueResolver.resolveStringValue( “${” + key + "}");
    }

}

說明: 通過${key}方式獲取key對應的屬性值;

獲取環境

@Component
public class EnvironmentUtils implements EnvironmentAware {

   private static Environment env;

    @Override
    public void setEnvironment(Environment environment) {
        EnvironmentUtils.env = environment;
    }

    public static String getEnvironmentStr() {
        String[] activeProfiles = env.getActiveProfiles();
        return activeProfiles[0];
    }
}

說明: 如果實際專案中啟用的profile有多個的話,可以返回陣列;