我有一个工作 Controller ,它有一项服务,如下所示。
@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 中工作和使用它。
@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;
}
...
}
服务和 Controller 都工作正常。
然后,在开发过程中,发现 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
的 View 时,它会因 Spring 错误而爆炸:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'filesController' defined in file [C:\rw_apps\tomcat\6.0.43-2\webapps\webquery\WEB-INF\classes\com\rockwell_collins\webquery\controller\FilesController.class]: Unsatisfied dependency expressed through constructor argument with index 1 of type [com.rockwell_collins.webquery.service.SearchService]: : Error creating bean with name 'searchService' defined in file [C:\rw_apps\tomcat\6.0.43-2\webapps\webquery\WEB-INF\classes\com\rockwell_collins\webquery\service\SearchService.class]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchService' defined in file [C:\rw_apps\tomcat\6.0.43-2\webapps\webquery\WEB-INF\classes\com\rockwell_collins\webquery\service\SearchService.class]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
Spring 只能将一项服务注入(inject)到 Controller 中吗? 我已经尝试在我的 spring xml 文件中指定“default-autowire”并尝试了所有可能的值,但没有任何效果。
最佳答案
您的 SearchService 是什么样子的?那里有一些静态 block 吗?
ExceptionInInitializerError '表示在静态初始化程序中发生了意外异常'
关于java - 在 Spring MVC 中使用@Controller、@Service 和@Inject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29377488/