JavaSpring3MVC控制器显式加载服务
我正在研究一些Spring3注释驱动的控制器和服务,有一个问题是如何做到这一点的JavaSpring3MVC控制器显式加载服务,java,spring,spring-mvc,spring-3,Java,Spring,Spring Mvc,Spring 3,我正在研究一些Spring3注释驱动的控制器和服务,有一个问题是如何做到这一点的 我在我的servlet context.xml文件中有以下要加载项的路径: 在控制器下,我在init类中有这个,init被标记为: @PostConstruct public void init() { ApplicationContext context = new GenericApplicationContext(); bizServices = (BizServices) context.
servlet context.xml文件中有以下要加载项的路径:
@PostConstruct
public void init() {
ApplicationContext context = new GenericApplicationContext();
bizServices = (BizServices) context.getBean("bizServices");
}
@Service("bizServices")
public class BizServicesImpl implements BizServices { ... }
在我的服务中,我有一个用于服务的bean,标记为:
@PostConstruct
public void init() {
ApplicationContext context = new GenericApplicationContext();
bizServices = (BizServices) context.getBean("bizServices");
}
@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中显式定位和加载此服务类?如果我让服务类从工厂加载,我可以指定工厂类是什么,这是xml中的bean配置条目吗
再次感谢…在@PostConstruct中,您正在实例化一个新的应用程序上下文。此新实例对原始ApplicationContext一无所知。
如果您试图访问bizServices,请在控制器中使用@Autowire annotation声明bizServices类型的字段。您没有完全实例化init方法上的上下文。您必须通过指定应用程序上下文xml的类路径位置来手动加载bean定义 从: 用法示例:
GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml")); // load your beans
PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
propReader.loadBeanDefinitions(new ClassPathResource("otherBeans.properties"));
ctx.refresh();
MyBean myBean = (MyBean) ctx.getBean("myBean");
使用如何?是否有任何错误?