1.以常见的web–service–dao模式为例
2.web
@Controller("web")
public class action {
@Resource(name = "service")
private ServiceImp serviceImp;
public ServiceImp getServiceImp() {
return serviceImp;
}
public void setServiceImp(ServiceImp serviceImp) {
this.serviceImp = serviceImp;
}
//传递/处理方法
public void do_some(String s){
System.out.println("现在Web层获取数据"+s+",交由Service处理");
serviceImp.do_some(s);
}
//定义初始化方法
@PostConstruct
public void init(){
System.out.println("Web层的初始化");
}
@PreDestroy
public void destory(){
System.out.println("Web层的销毁");
}
}
2.Service
(这里只是演示,没有接口也行)
@Component("service")
public class ServiceImp implements Service{
@Resource(name = "dao")
private Dao dao;
public Dao getDao() {
return dao;
}
public void setDao(Dao dao) {
this.dao = dao;
}
@Override
public void do_some(String s) {
System.out.println("现在数据"+s+"已经从Web层发过来了,转交给Service处理");
dao.do_some(s);
}
}
3.dao
@Repository("dao")
public class Dao {
public void do_some(String s){
System.out.println("现在数据"+s+"已经从Service层发过来了,转交给Dao处理");
}
}
4.test
public class Test5 {
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans12.xml");
action action= (spring.web_action.action) context.getBean("web");
action.do_some("hello");
context.close();
}
}
5.result
Web层的初始化
现在Web层获取数据hello,交由Service处理
现在数据hello已经从Web层发过来了,转交给Service处理
现在数据hello已经从Service层发过来了,转交给Dao处理
Web层的销毁
6.感想
(1)传递的过程中,注意下一层级的初始化,如果不用@Resource注解去自动填充的话,会报空指针异常。
本文详细解析了基于Spring框架的Web-Service-Dao三层架构,通过具体代码示例,展示了如何实现各层间的依赖注入与数据传递过程。从Web层到Service层,再到Dao层,每一步都清晰地说明了数据的处理流程及各层的初始化和销毁过程。
188

被折叠的 条评论
为什么被折叠?



