spring 的 Dao层+Service层+Action层的初使用,为什么用spring
spring 的 Dao层+Service层+Action层的初使用,为什么用spring
1.Dao层:(分为接口与Implement)
package com.myget;
public interface PersonDao {
public void add();
}
+
package com.myget;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
@Repository("personDao") // 相当于<bean id="personDao" class="com.myget.PersonDaoImplement" />
public class PersonDaoImplement implements PersonDao {
public void add(){
System.out.println("Dao层的add方法");
}
}
2.Service层:(接口与implement)
package com.myget;
public interface ServiceInterface {
public void add();
}
+
package com.myget;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
@Service("serviceImplement") //<bean id="serviceImplement" class="com.myget.ServiceImplement" />
public class ServiceImplement implements ServiceInterface{
public PersonDao personDao;
/* @Resource(name="personDao") //引入id为personDao的 personDaoImplement类 <bean id="serviceImplement" class="com.myget.ServiceImplement"> <property name="personDao" ref=‘personDao”> </bean>
public PersonDao personDao;
public PersonDao getPersonDao(){ //相当于getter方法 跟 下面的setter方法功能差不多啊 赶脚
return personDao;
}*/
@Resource(name="personDao")
public void setPersonDao(PersonDao personDao){
this.personDao=personDao;
}
public void add(){
System.out.println("service层的add方法");
personDao.add();
}
}
3.Action层(类的getter方法与setter方法,选一个)
package com.myget;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
@Controller("actionExample") //相当于<bean id="actionExample" class="com.myget.ActionExample" />
public class ActionExample {
@Resource(name="serviceImplement") //相当于在bean中引用了id为serviceImplement的bean <bean id="serviceImplement" class="com.myget.ActionExample"><property name="serviceImplement" ref="serviceImplement"></bean>
public ServiceInterface serviceInterface;
public ServiceInterface getServiceInterface(){ //
return serviceInterface;
}
/* @Resource(name="serviceImplement")
public void setServiceInterface(ServiceInterface serviceInterface){
this.serviceInterface=serviceInterface;
}*/
public void addadd(){
serviceInterface.add();//调用Dao层与Service层的add方法
System.out.println("action层的addadd方法");
}
}
4.最后
调用ApplicationContext:
package com.myget;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyResult {
public static void main(String[] args){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Example.xml");
ActionExample actionExample=(ActionExample)applicationContext.getBean("actionExample");
actionExample.addadd();
}
}
相关文章
- 暂无相关文章
用户点评