SpringMVC Dao层注入到Service层,Service层注入到controller层及相关XML

1 本人新手,刚开始学习SringMVC框架,需要各个层之间的注入。

举个例子:

最初,在dao层实现service的方式是,new出来一个(每个方法都要new一次)。

IServiceImpl service =new IServiceImpl();

service.fill();//fill是我服务中的方法

 完成注入之后,每个方法使用service如下:

service.fill();//service提前声明了。下面会声明

2 Service层注入到controller层

首先在Service的实现类中添加如下代码:

@Service("Service")//要添加的
public class IServiceImpl implements IService { //这是我的service实现类

然后,在controller类中添加如下代码:

public class Testcontroller {//这是我的controller实现类
     @Autowired//要添加的
     @Qualifier("Service")//要添加的
    private IServiceImpl service;//要添加的,这是上文提及的声明

接下来你在controller的方法中就可以直接使用:

service.fill();//fill是我服务中的方法

3Dao层注入到Service层

和 "Service层注入到controller层"样式差不多

在Dao实现类上面加入:

@Repository(value="userDao")//要添加的

public class IDaoImpl implements IDao {//我的Dao层实现类

然后在Service实现类中添加:

public class IServiceImpl implements IService {//这是我的service实现类
     //@Autowired
     @Resource(name = "userDao")//要添加的

4 XML文件的设置(需要添加的那一行)

Spring-dao.xml

 <context:compoSpring-mvc.xmlnent-scan base-package="com.test.dao.impl"/>//com.test.dao.impl是我的IDaoImpl所在的包

Spring-service.xml

 <context:component-scan base-package="com.test.service.impl"/>//com.test.service.impl是我的IServicempl所在的包

当然,你也在你的Spring-mvc.xml中填入下面的话,也是OK的,目的是为了将你包中的类扫描出来

 <context:component-scan base-package="com.testl"/>//com.test.dao.impl是我的IDaoImpl所在的包
    

猜你喜欢

转载自blog.csdn.net/qq_41306610/article/details/84584125