1. 程式人生 > >Spring(21) 獲取其他類成員變數的值

Spring(21) 獲取其他類成員變數的值

  1. 可以在配置檔案中通過將class指定為PropertyPathFactory,然後就可以通過指定targetClass配合targetField來將別人的成員變數拿過來用啦~~
    <?xml version="1.0" encoding="GBK"?>
    <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
    	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    
        <!--將class指定為FieldRetrievingFactoryBean,然後再指定 targetClass和targetField,就ok-->
        <bean id="theAge1" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean ">
            <property name="targetClass" value="java.sql.Connection"/>
            <property name="targetField" value="TRANSACTION_READ_UNCOMMITTED"/>
        </bean>
    
    <!--這是簡寫,如果這裡是例項變數那麼staticField就要改啦-->
        <bean id="theAge2" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean ">
            <property name="staticField" value="java.sql.Connection.TRANSACTION_NONE"/>
        </bean>
    
        <!--一種比較高階的寫法-->
        <bean id="test" class="InstancePackage.Test">
            <property name="show">
                <!--<bean id="java.sql.Connection.TRANSACTION_NONE"-->
                      <!--class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>-->
                <util:constant static-field="java.sql.Connection.TRANSACTION_NONE"/>
            </property>
        </bean>
    
    </beans>
    package InstancePackage;
    
    public class Test {
        private int show;
    
        public int getShow() {
            return show;
        }
    
        public void setShow(int show) {
            this.show = show;
        }
    }
    
    package TestPackage;
    
    import InstancePackage.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class SpringTest {
        public static void main(String []args){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
            System.out.println( applicationContext.getBean("theAge1",Integer.class));
            System.out.println( applicationContext.getBean("theAge2",Integer.class));
            System.out.println( applicationContext.getBean("test", Test.class).getShow());
        }
    }
    

    這是我看李剛編著的《輕量級javaEE企業應用實戰(第五版)-Struts2+Spring5+Hibernate5/JAP2》後總結出來的。