本文博客地址:http://www.jb51.cc/article/p-byoifxxv-bps.html(转载请注明出处)
内部对象就是对象的里面还有对象。。。。。好象是废话。
比如订单Order中,包含一个消费者Customer。那么Customer就是Order对象的内部对象。(有人叫内部类,我觉得不妥。内部类是指一个类的定义放在另一个类的内部,而这里是一个对象使用了另一个对象作为成员属性)
Customer类:
@H_502_10@public @H_502_10@class Customer {
@H_502_10@private String name;
@H_502_10@private String address;
@H_502_10@private @H_502_10@int age;
//getter and setter methods
@Override
@H_502_10@public String toString() {
@H_502_10@return "Person [address=" + address + ",age=" + age + ",name=" + name + "]";
}
}
Order类:
@H_502_10@public @H_502_10@class Order {
/*comstomer和notifyservice都是Order的内部对象*/
@H_502_10@private Customer customer;
@H_502_10@private String orderno;
@H_502_10@private NotifyService notifyservice;
@H_502_10@public Order(){
@H_502_10@this.customer=@H_502_10@new Customer();
}
@H_502_10@public Order(Customer customer,String orderno,NotifyService notifyservice) {
super();
@H_502_10@this.customer = customer;
@H_502_10@this.orderno = orderno;
@H_502_10@this.notifyservice = notifyservice;
}
//getter and setter methods......
/*订单支付完成后,系统通知老板*/
@H_502_10@public @H_502_10@void PaySuccess(){
notifyservice.sendMessage("客户"+customer.getName()+"完成订单"+orderno+"付款,共人民币:97.5元");
}
}
然后在beans.xml定义bean对象
<bean id="order" class="twm.spring.start.Order">
<@H_502_10@property name="customer">
<bean class="twm.spring.start.Customer">
<@H_502_10@property name="name" value="陈先生"></@H_502_10@property>
<@H_502_10@property name="address" value="深圳南山区"></@H_502_10@property>
</bean>
</@H_502_10@property>
<@H_502_10@property name="orderno" value="201799777799"></@H_502_10@property>
<@H_502_10@property name="notifyservice" @H_502_10@ref="notify2"></@H_502_10@property>
</bean>
<bean id="notifyfactory" class="twm.spring.start.NotifyFactory" />
<bean id="notify2" factory-bean="notifyfactory" factory-method="getNotifyService" />
如果用构造注入则是:
<bean id="order" class="twm.spring.start.Order">
<constructor-arg name="customer">
<bean class="twm.spring.start.Customer">
<property name="name" value="陈先生"></property>
<property name="address" value="深圳南山区"></property>
</bean>
</constructor-arg>
<constructor-arg name="orderno" value="201799777799"></constructor-arg>
<constructor-arg name="notifyservice" ref="notify2"></constructor-arg>
</bean>
<bean id="notifyfactory" class="twm.spring.start.NotifyFactory" />
<bean id="notify2" factory-bean="notifyfactory" factory-method="getNotifyService" />
setter注入和构造注入中,在<property>
元素或者<constructor-arg>
元素内定义<bean>
元素,就是所谓的内部类。
比如当“陈先生”这个用户只用在order2这个bean中使用,就没必要在外面定义“陈先生”这个bean,再通过order2内部的ref引用了。
直接定义在order的<property>
元素或者<constructor-arg>
元素内定义“陈先生”bean更直观。
内部bean的定义无需id或name;容器会忽略这些属性,也会忽略scope标记。内部通常是匿名的,伴随着外部类(的创建)而创建 。
本文博客地址:http://www.jb51.cc/article/p-byoifxxv-bps.html(转载请注明出处)