6.笔记JAVA框架学习——Bean配置Properties属性
继续上节的学习笔记。
在app.xml文件中,增加如下,配置bean:
<bean id="service"class="Service">
<property name="dao">
<!-- 内部 bean,类似于匿名内部类对象. 不能被外部的 bean 来引用, 也没有必要设置 id 属性 -->
<bean class="Dao">
<property name="dataSource"value="c3p0"></property>
</bean>
</property>
</bean>
<bean id="action"class="Action">
<property name="service"ref="service"></property>
<!-- 设置级联属性(了解) -->
<property name="service.dao.dataSource"value="DBCP2"></property>
</bean>
增加action.java内容如下:
publicclass Action {
private Service service;
publicvoidsetService(Service service) {
this.service= service;
}
public ServicegetService() {
returnservice;
}
publicvoid execute(){
System.out.println("Action's execute...");
service.save();
}
}
修改主函数,main.java如下:
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
//1. 创建 Spring 的 IOC 容器
ApplicationContext apx = newClassPathXmlApplicationContext("app.xml");
Service service = (Service)apx.getBean("service");
System.out.println(service);
service.save();
}
}
执行如下:
Dao'sConstructor...
Service@72d818d1
Service'ssave
save by DBCP2