package model;
//本頁是java組態
//id是方法名稱,class是回傳值
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringJavaConfig {
// <bean id="date1" class="java.util.Date"></bean>
@Bean
public java.util.Date date1() {
return new java.util.Date(100000000000000L);
}
// <bean id="demoBean" class="model.DemoBean">
//DemoBean物件有一個方法是setDate,要放日期物件進去
// public void setDate(java.util.Date date) {
// this.date = date;
// }
// <property name="date" ref="date"></property>
// </bean>
@Bean
public DemoBean demoBean() {
DemoBean demoBean = new DemoBean();//先new自己要回傳型別的物件
demoBean.setDate(date1());
return demoBean;
}
// <bean id="demoDAO" class="model.DemoDAO">
// <property name="demoBean" ref="demoBean"></property>
// </bean>
//DAO中有一個setDemoBean的方法
// public void setDemoBean(DemoBean demoBean) {
// this.demoBean = demoBean;
// }
@Bean
public DemoDAO demoDAO() {
DemoDAO demoDAO = new DemoDAO();
demoDAO.setDemoBean(demoBean());
return demoDAO;
}
// <bean id="demoService" class="model.DemoService"> <property
// name="demoDAO" ref="demoDAO"></property> </bean>
@Bean
public DemoService demoService() {
DemoService demoService = new DemoService();
demoService.setDemoDAO(demoDAO());
return demoService;
}
}
package test;
import model.DemoBean;
import model.DemoDAO;
import model.DemoService;
import model.SpringJavaConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestClass {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(SpringJavaConfig.class);
DemoBean demoBean=(DemoBean) context.getBean("demoBean");
System.out.println("DemoBean="+demoBean);
DemoDAO demoDAOAn01=(DemoDAO) context.getBean("demoDAO");
System.out.println("DemoBean="+demoDAOAn01);
DemoService demoServiceAn01=(DemoService) context.getBean("demoService");
System.out.println("DemoBean="+demoServiceAn01);
((ConfigurableApplicationContext) context).close();
}
}
留言列表