在Spring MVC中使用@ Controller,@ Service和@Inject

时间:2015-03-31 19:59:26

标签: java spring spring-mvc tomcat

我有一个工作的控制器有一个服务,如下所示。

@Controller
public class FileController 
{
   private FileService   fileService;       // service injected by Spring

   /**
    * constructor which initializes the file service.
    * @param fileService     service used to retrieve a list of files
    */
   @Inject
   public FileController(FileService fileService)
   {
      this.fileService = fileService;
   }

   ...
}

同样,我还有另一项服务,我也在其他服务器上工作和使用。

@Controller
public class SearchController 
{
   private SearchService searchService;       // service injected by  Spring

   /**
    * constructor which initializes the search service.
    * @param searchService     service used to search for items
    */
   @Inject
   public SearchController(SearchService searchService)
   {
      this.searchService = searchService;
   }

   ...
}

服务和控制器都运行良好。

然后,在开发过程中,结果FileController也需要搜索服务,因此我修改了FileController,如下所示。

@Controller
public class FilesController
{
   // data members
   private FileService   fileService;       // service injected by Spring
   private SearchService searchService;     // service injected by Spring

   /**
    * constructor which initializes the file service.
    * @param fileService     service used to retrieve a list of files
    * @param searchService   service used to retrieve a list of items.
    */
   @Inject
   public FilesController(FileService fileService, SearchService searchService)
   {
      this.fileService   = fileService;
      this.searchService = searchService;
   }
   ...
}

这个编译得很好并且部署得很好,但是当我访问使用FileController的视图时,它会因Spring错误而爆炸:

  

org.springframework.beans.factory.BeanCreationException:错误   用名字创建bean   'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0':   bean的初始化失败;嵌套异常是   org.springframework.beans.factory.UnsatisfiedDependencyException:   创建名为'filesController'的bean在文件中定义时出错   [C:\ rw_apps \ Tomcat的\ 6.0.43-2 \ web应用\ webquery \ WEB-INF \类\ COM \ rockwell_collins \ webquery \控制器\ FilesController.class]:   通过构造函数参数表示不满意的依赖关系   [com.rockwell_collins.webquery.service.SearchService]类型的索引1:   :创建文件中定义名称为“searchService”的bean时出错   [C:\ rw_apps \ Tomcat的\ 6.0.43-2 \ web应用\ webquery \ WEB-INF \类\ COM \ rockwell_collins \ webquery \服务\ SearchService.class]:   bean的实例化失败;嵌套异常是   java.lang.ExceptionInInitializerError;嵌套异常是   org.springframework.beans.factory.BeanCreationException:错误   在文件中定义名为'searchService'的bean   [C:\ rw_apps \ Tomcat的\ 6.0.43-2 \ web应用\ webquery \ WEB-INF \类\ COM \ rockwell_collins \ webquery \服务\ SearchService.class]:   bean的实例化失败;嵌套异常是   java.lang.ExceptionInInitializerError

Spring是否只能将一个服务注入控制器? 我已经尝试在我的spring xml文件中指定“default-autowire”并尝试了所有可能的值,但没有任何效果。

1 个答案:

答案 0 :(得分:0)

您的SearchService如何?那里有一些静态块吗?

ExceptionInInitializerError'表示静态初始化程序中出现意外异常'