【问题标题】:Inject singleton on spring mvc controller在spring mvc控制器上注入单例
【发布时间】:2015-06-02 12:40:25
【问题描述】:

我有一个单例类:

@Singleton
public class CacheManager {
    ...
}

在我的控制器中,我想注入这个单例:

@Controller
@RequestMapping("/myRequest.do")
public class ListeSinistresController extends AFoaGanController {

    @Autowired
    private CacheManager cacheManager;

    ...
}

部署时出现以下错误:

<2 juin 2015 14 h 31 CEST> <Warning> <HTTP> <BEA-101162> <User defined listener org.springframework.web.context.ContextLoaderListener failed:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'listeSinistresController': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.blabla.cache.CacheManager 
com.blabla.web.controller.personne.ListeSinistresController.cacheManager; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.blabla.cache.CacheManager] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency. 

我尝试用@Inject - @Authowired - @EJB 注入我的单身人士,但没有任何效果。

这样做的方法是什么?

【问题讨论】:

  • com.blabla.cache 包是否配置为被 Spring 扫描?
  • 配置在哪个文件中?
  • 好的,我在一个 xml 文件中找到了这个: 这是你告诉我的吗?

标签: java spring spring-mvc dependency-injection


【解决方案1】:

Singleton 的包导入是什么?你可以试试@Component 注释吗? (提示:所有 spring bean 默认都是单例,如果没有明确配置为prototype)。

如果上述方法不起作用,请同时显示您的应用程序配置。那么包扫描可能是不正确的。

你必须将@Autowired与spring一起使用,这是正确的。

【讨论】:

  • 单例在 com.blabla.cache 包中。控制器在 com.blabla.web.controller.personne 包中。 @Component 不起作用。
  • 我在配置文件中添加了这个,但没有用:
猜你喜欢
  • 2014-11-06
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 2012-11-04
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多