我正在研究一些 Spring 3 注释驱动的 Controller 和服务,并且有一个关于如何实现这一点的问题?
我的
servlet-context.xml
中有归档以下要加载的项目的路径:<context:component-scan base-package="com.project.controller, com.project.service"/>
在 Controller 下,我在 init 类中有这个,并且 init 被标记为:
@PostConstruct
public void init() {
ApplicationContext context = new GenericApplicationContext();
bizServices = (BizServices) context.getBean("bizServices");
}
在我的服务中,我有一个服务 bean,标记为:
@Service("bizServices")
public class BizServicesImpl implements BizServices { ... }
我得到的异常是:
SEVERE: Allocate exception for servlet Spring MVC Dispatcher Servlet
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'bizServices' is defined
这告诉我要么我使用了错误的应用程序上下文服务,要么找不到 bean。我可以在没有 Autowire 的情况下在 PostConstruct 中显式定位并加载此 Service 类吗?如果我从工厂加载我的服务类,我可以指定工厂类是什么吗?它会是 xml 中的 bean 配置条目吗?
再次感谢...
最佳答案
在 @PostConstruct 中,您正在实例化一个新的 ApplicationContext。这个新实例对原始ApplicationContext一无所知。 如果您想要做的是访问 bizServices,请在 Controller 中使用 @Autowire 注释声明 BizServices 类型的字段。
关于Java Spring 3 MVC Controller 显式加载服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5689898/