Spring MVC使用自动对象外部控制器类

时间:2015-12-25 11:06:12

标签: java spring spring-mvc

我正在为我的项目使用Spring MVC。是否可以在另一个类上使用相同的自动对象?

我有两个控制器,一个用于导航,另一个用于操作。

这是我的示例导航控制器:

@Controller
public class NavigationController {

    @Autowired
    private DepartmentDAO deptDao;

    @RequestMapping("/")
    public ModelAndView panel() {
      ModelAndView mv = new ModelAndView("panel");
      Department dept = deptDao.getDept();
      mv.addObject("department",dept);
      return mv;
    }
}

然后我的操作控制器:

 @Controller
 public class OperationController {

    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public ModelAndView saveEvent(){
      ModelAndView mv = new ModelAndView("next");
      Event event = new EventCreator().createEvent();
      //some logic here
      return mv;
    }
 }

这是我的业务代表类:

public class EventCreator {
  public Event createEvent(){
   //logic here
   //I need to use the deptDao here.
  }
}

非常感谢你!

2 个答案:

答案 0 :(得分:2)

您可以在DepartmentDAO课程中简单地自动装配EventCreator,就像您在NavigationController课程中自动装配它一样。确保使用EventCreator@Component类进行注释,并将其包含在组件扫描完成的包中,以便spring将自动装配DepartmentDao类中的EventCreator。< / p>

@Component
public class EventCreator {

  @Autowired
  private DepartmentDAO deptDao;

  public Event createEvent(){
   //logic here
   //I need to use the deptDao here.

  //deptDao.getAllDepartments();

  }
}

答案 1 :(得分:2)

你可以在另一个spring bean对象中@Autowired一个spring bean对象

<强>假设

  

我假设您已使用@Repository声明了DepartmentDAO   注释,因为您没有包含DepartmentDAO的代码   问题

有两种方法可以解决您的问题

  
      
  1. 一个很好的解释是@TimeTravel annotate EventCreator with   @Component with create spring bean,你可以轻松自动装配   EventCreator类中的DepartmentDAO

  2.   
  3. 因为你有两个控制器类使它成为Spring bean,因为它们是用@Controller注释的,你可以做什么你可以自动装配   departmentDAO在OperationController类中传递实例   DepartmentDAO作为EventCreator类构造函数

  4. 中的参数   
@Controller
public class OperationController {
@Autowired
private DepartmentDAO deptDao;

@RequestMapping(value = "/save.do", method = RequestMethod.POST)
public ModelAndView saveEvent(){
  ModelAndView mv = new ModelAndView("next");
  Event event = new EventCreator(deptDao).createEvent();
  //some logic here
  return mv;
  }
 }


public class EventCreator {

 private DepartmentDAO deptDao=null; 

 public EventCreator(DepartmentDAO deptDaoAsArg){
  deptDao=deptDaoAsArg;
 }

 public Event createEvent(){
 //logic here
 //I need to use the deptDao here.
 }
}