Method of of spring to read the spring configuration file

  • 2020-04-01 02:59:42
  • OfStack

1. Spring configuration file


<bean id="configproperties" 
         class="org.springframework.beans.factory.config.PropertiesFactoryBean">
          <property name="location" value="classpath:jdbc.properties"/>
    </bean>

2. Read the attribute method


ApplicationContext c=new ClassPathXmlApplicationContext("classpath:applicationContext-datasource.xml");
Properties p=(Properties)c.getBean("configproperties");
System.out.println(p.getProperty("jdbcOrcale.driverClassName"));


Another friend offers a way to read a spring configuration file

Direct reading method:

public void test() throws IOException
 {
  Resource resource = ApplicationContextFactory.getApplicationContext().getResource("classpath:com/springdemo/resource/test.txt");

  File file = resource.getFile();
  byte[] buffer =new byte[(int) file.length()];
  FileInputStream is =new FileInputStream(file);
  is.read(buffer, 0, buffer.length);

  is.close();
  String str = new String(buffer);
  System.out.println(str); 
 }

Read by spring configuration:


package com.springdemo.resource;
import org.springframework.core.io.Resource;
public class ResourceBean {
 private Resource resource;
 public Resource getResource() {
  return resource;
 }
 public void setResource(Resource resource) {
  this.resource = resource;
 }
}

Spring bean configuration:


 <!--  You can directly assign a file path to Resource The type of resource attribute ,spring Will be automatically converted to the corresponding path Resource -->
 <bean id="resourceBean" class="com.springdemo.resource.ResourceBean" >
  <property name="resource" value="classpath:/com/springdemo/resource/test.txt" ></property>
 </bean>


Related articles: