PropertiesLoaderUtils

来源:互联网 发布:北师珠网络教学 编辑:程序博客网 时间:2024/05/21 17:42
public static String getProperty(String resourcePaht,String key)
{
String result = "";
Resource resource = new ClassPathResource(resourcePaht);

try
{
Properties props = PropertiesLoaderUtils.loadProperties(resource);
result = props.getProperty(key);

} catch (IOException e)
{
e.printStackTrace();
}
return result;

}



 private Properties getvaluebyProperty(ApplicationContext context) {
        AbstractApplicationContext abstractContext = (AbstractApplicationContext) context;
        Properties properties = new Properties();
        try {
            // get the names of BeanFactoryPostProcessor
            String[] postProcessorNames = abstractContext.getBeanNamesForType(
                    PropertyPlaceholderConfigurer.class, true, true);


            for (String ppName : postProcessorNames) {
                System.out.println(ppName);
                // get the specified BeanFactoryPostProcessor
                PropertyPlaceholderConfigurer beanProcessor = abstractContext.getBean(ppName,
                        PropertyPlaceholderConfigurer.class);
                // check whether the beanFactoryPostProcessor is
                // instance of the PropertyResourceConfigurer
                // if it is yes then do the process otherwise continue
                if (beanProcessor instanceof PropertyResourceConfigurer) {
                    PropertyResourceConfigurer propertyResourceConfigurer = (PropertyResourceConfigurer) beanProcessor;


                    // get the method mergeProperties
                    // in class PropertiesLoaderSupport
                    Method mergeProperties = PropertiesLoaderSupport.class
                            .getDeclaredMethod("mergeProperties");
                    // get the props
                    mergeProperties.setAccessible(true);
                    Properties props = (Properties) mergeProperties
                            .invoke(propertyResourceConfigurer);


                    // get the method convertProperties
                    // in class PropertyResourceConfigurer
                    Method convertProperties = PropertyResourceConfigurer.class.getDeclaredMethod(
                            "convertProperties", Properties.class);
                    // convert properties
                    convertProperties.setAccessible(true);
                    convertProperties.invoke(propertyResourceConfigurer, props);


                    properties.putAll(props);
                }
            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return properties;
    }

0 0