method to read the spring configuration file (Spring reads the resource file) _java

Source: Internet
Author: User

1.spring configuration file

Copy Code code as follows:

<bean id= "Configproperties"
class= "Org.springframework.beans.factory.config.PropertiesFactoryBean" >
<property name= "Location" value= "Classpath:jdbc.properties"/>
</bean>

2. Read Property methods

Copy Code code as follows:

ApplicationContext c=new classpathxmlapplicationcontext ("Classpath:applicationcontext-datasource.xml");
Properties P= (properties) C.getbean ("Configproperties");
System.out.println (P.getproperty ("Jdbcorcale.driverclassname"));


Another friend provides a way to read the spring configuration file and share it.

Direct Read mode:
Copy Code code as follows:

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 through Spring configuration:

Copy Code code as follows:

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:

Copy Code code as follows:

<!--can assign a file path directly to the resource property of the resource type, and spring will automatically convert to the corresponding resource based on the path-->
<bean id= "Resourcebean" class= "Com.springdemo.resource.ResourceBean" >
<property name= "Resource" value= "Classpath:/com/springdemo/resource/test.txt" ></property>
</bean>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.