Java Read the properties file

Source: Internet
Author: User

First, Target: Read the properties file, get the class name to generate the object

Second, class

1.movable.java

public interface Movable {void run ();

  

2.car.java

Public class Car implements movable {public void run () {System.out.println ("Car running .....");}}

  

3.spring.properties

PS: "=" cannot have spaces on either side

Vechiletype=com.tong.spring.factory.car

  

4.test.java

public class Test {@org. junit.testpublic void Test () {//reads the properties file, obtains the class name to generate the object properties Pros = new properties (); try {/ /1. Read the class name to instantiate Pros.load (Test.class.getClassLoader (). getResourceAsStream ("com/tong/spring/factory/ Spring.properties ")); String Vechiletype = Pros.getproperty ("Vechiletype");//2. Use reflection to load classes and instantiate classes with newinstance () object o = Class.forName ( Vechiletype). newinstance (); Movable m = (movable) o;m.run ();} catch (Exception e) {e.printstacktrace ();}}}

  

5. Operation Result:

6. If you change to spring to read the XML file, when spring is configured, add Applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans"       Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"       xsi:schemalocation= "http://www.springframework.org/ Schema/beans           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">  <bean id=" vehicle "class=" Com.tong.spring.factory.Car ">  </bean>  <!--more beans definitions go here--></ Beans>

  

7.test.java change to the following

public class Test {@org. junit.testpublic void Test () {Beanfactory factory = new Classpathxmlapplicationcontext (" Applicationcontext.xml "); Object o = Factory.getbean (" vehicle "); Movable m = (movable) o;m.run ();}}

  

Java Read the properties file

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.