2015年12月23日 星期三

Compound property names 和 空與null (Spring3.x 八)

※Compound property names 

不知道怎麼翻譯會比較傳神,反正就是多層賦值的意思,看範例


三個VO

public class Book {
    private Comic ooo;
    // setter/getter...
}
    
public class Comic {
    private Cartoon xxx;
    // setter/getter...
}
    
public class Cartoon {
    private String oooxxx;
    // setter/getter...
}

applicationContext.xml

<bean id="book1" class="book.vo.Book">
    <property name="ooo">
        <bean class="book.vo.Comic">
            <property name="xxx">
                <bean class="book.vo.Cartoon">
                    <property name="oooxxx" value="海綿寶寶" />
                </bean>
            </property>
        </bean>
    </property>
</bean>
    
<bean id="co" class="book.vo.Comic" />
<bean id="ca" class="book.vo.Cartoon" />
<bean id="book2" class="book.vo.Book">
    <property name="ooo" ref="co" />
    <property name="ooo.xxx" ref="ca" />
    <property name="ooo.xxx.oooxxx" value="喜洋洋與灰太郎" />
</bean>
    
<bean id="book3" class="book.vo.Book">
    <property name="ooo">
        <bean class="book.vo.Comic" />
    </property>
    
    <property name="ooo.xxx">
        <bean class="book.vo.Cartoon" />
    </property>
    
    <property name="ooo.xxx.oooxxx" value="灰太郎追喜洋寶寶" />
</bean>

測試類

ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    
Book book1 = (Book) appContext.getBean("book1");
Book book2 = (Book) appContext.getBean("book2");
Book book3 = (Book) appContext.getBean("book3");
System.out.println(book1.getOoo().getXxx().getOooxxx());
System.out.println(book2.getOoo().getXxx().getOooxxx());
System.out.println(book3.getOoo().getXxx().getOooxxx());
    
((ClassPathXmlApplicationContext) appContext).close();

※結果:
海綿寶寶
喜洋洋與灰太郎
灰太郎追喜洋寶寶

※book1為之前介紹的內部bean; book2和book3就是多層賦值了

※多層賦值要保證每一層都不是null,所以才會多宣告co和ca,如果不想宣告就用book3的方法




※空與null


Book.java

public class Book {
    private String bookName;
    // setter/getter...
}

applicationContext.xml

<bean id="book1" class="book.vo.Book" />
    
<bean id="book2" class="book.vo.Book">
    <property name="bookName">
        <null />
    </property>
</bean>
    
<bean id="book3" class="book.vo.Book">
    <property name="bookName" value="" />
</bean>

測試類

ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    
Book book1 = (Book) appContext.getBean("book1");
Book book2 = (Book) appContext.getBean("book2");
Book book3 = (Book) appContext.getBean("book3");
System.out.println(book1.getBookName());
System.out.println(book2.getBookName());
System.out.println(book3.getBookName().length());
    
((ClassPathXmlApplicationContext) appContext).close();

※結果:
null
null
0

※宣告property一定要給value或ref,不然會報錯,但其實還可以用null標籤

沒有留言:

張貼留言