Java Spring 3 MVC 控制器显式加载服务
我正在研究一些 Spring 3 注释驱动的控制器和服务,并且有一个关于这如何可能的问题?
我的
servlet-context.xml
文件中有要加载的以下项目的路径:
在控制器下,我在 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 配置条目吗?
再次感谢...
I'm working through some of Spring 3 annotation driven controllers and services and had a question on how this could be possible?
I have in my
servlet-context.xml
file the paths for the following items to be loaded:<context:component-scan base-package="com.project.controller, com.project.service"/>
Under a controller I have this in the init class, and the init is tagged as:
@PostConstruct
public void init() {
ApplicationContext context = new GenericApplicationContext();
bizServices = (BizServices) context.getBean("bizServices");
}
In my Services I have a bean for services tagged as:
@Service("bizServices")
public class BizServicesImpl implements BizServices { ... }
I get the exception as:
SEVERE: Allocate exception for servlet Spring MVC Dispatcher Servlet
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'bizServices' is defined
This tells me either I am using the wrong application context service or the bean cannot be found. Can I locate and load this Service class explicitly in the PostConstruct without Autowire? What if I made my services classes loaded from a factory, can I designate what the factory class is, and would that be a bean config entry in the xml?
Thanks again...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 @PostConstruct 中,您正在实例化一个新的 ApplicationContext。这个新实例对原始ApplicationContext一无所知。
如果您想要访问 bizServices,请在控制器中使用 @Autowire 注释声明 BizServices 类型的字段。
In your @PostConstruct you are instantiating a new ApplicationContext. This new instance doesn't know anything about the original ApplicationContext.
If what you are trying to do is to get access to bizServices, in your controller declare a fields of type BizServices with @Autowire annotation.
您没有完全实例化 init 方法上的上下文。您必须通过指定应用程序上下文 xml 的类路径位置来手动加载 bean 定义。
来自 GenricApplicationContext javadoc:
用法示例:
You are not instantiating the context on your init method completely. You will have to manually load the bean definitions by specifying the classpath location of your application context xml.
From the GenricApplicationContext javadoc:
Usage example: