what's the mechanism of xml in spring during t

2019-09-17 16:24发布

When I need to use Property Place Holder, I just define a bean in spring_config.xml as follows, without doing anything to this bean in java code, how could the spring know that?

    <bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" 
        p:location="spring_test/spring.properties"></bean> 

another confused part is alike: I define two beans in spring_config.xml, namely SqlSessionFactoryBean and MapperFactoryBean, how could spring implement that the MapperFactoryBean acts just like a proxy to my DAO without I having to write any java code?

Is there any article on the mechanism of xml parsing or something related? Thanks a lot!

1条回答
做个烂人
2楼-- · 2019-09-17 16:52

You need to know about Java Reflection. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. below is simple example.

 package com.example;

    public class Emplyoee {    
        private String name;
        public Emplyoee() {
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        } 

        public static void main(String args[]) {
            String className = "com.example.Emplyoee";
            try {
                 //finds class, casts Emplyoee class
                  Class<Emplyoee> klass = ((Class<Emplyoee>) Class.forName(className ));
                 //instantiate new objects,notice Emplyoee class
                 Emplyoee theNewObject = klass.newInstance();
                 //set value 
                 theNewObject.setName("john");
                 //calls "name" by getter method,and prints "john"
                 System.out.println(theNewObject.getName());

            } catch (ClassNotFoundException e) {
                 e.printStackTrace();
            } catch (InstantiationException e) {
                 e.printStackTrace();
            } catch (IllegalAccessException e) {
                 e.printStackTrace();
            }
       }
    }

The Spring container will find "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" class by "forName" method and instantiate "PropertyPlaceholderConfigurer" class.

查看更多
登录 后发表回答