用注解的方式结合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>