SpringMVC和Spring的結合方式二
阿新 • • 發佈:2018-12-10
用註解的方式結合SpringMVC和Spring CatController.java
package com.bwf.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.bwf.service.ICatService; @Controller public class CatController { @Autowired private ICatService catService; @RequestMapping("cat") public String cat(){ System.out.println(catService); catService.show(); return "index"; } }
ICatService.java
package com.bwf.service;
public interface ICatService {
public void show();
}
CatService.java
package com.bwf.service; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import com.bwf.dao.ICatDAO; @Service public class CatService implements ICatService { @Resource private ICatDAO catDAO; @Override public void show() { System.out.println("貓的叫聲......"); catDAO.find(); } }
ICatDAO.java
package com.bwf.dao;
public interface ICatDAO {
public void find();
}
CatDAO.java
package com.bwf.dao; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; @Repository public class CatDAO implements ICatDAO{ @Override public void find() { System.out.println("資料庫層的貓的操作........"); } }
總結:
- Controller層匯入service(不用通過配置檔案注入了),使用@AutoWired或@Resource自動織入
- Service層,先用註解@Service或@Component修飾Service類,再使用@Resource匯入DAO
- DAO層,用註解@Repository修飾DAO類
注意: 每一層都要配置元件掃描
<!-- 註解驅動 自動去掃描到註解的類 -->
<context:component-scan base-package="com.bwf.controller"></context:component-scan>
<context:component-scan base-package="com.bwf.service"></context:component-scan>
<context:component-scan base-package="com.bwf.dao"></context:component-scan>