SpringMVC和Spring的结合方式二

用注解的方式结合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("数据库层的猫的操作........");
		
	}	
	
}

总结:

  1. Controller层导入service(不用通过配置文件注入了),使用@AutoWired或@Resource自动织入
  2. Service层,先用注解@Service或@Component修饰Service类,再使用@Resource导入DAO
  3. 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>

猜你喜欢

转载自blog.csdn.net/yicha_i/article/details/82778128