Java Spring 3 MVC Controllers explicitly load Services
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.No开发者_JAVA技巧SuchBeanDefinitionException: 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...
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.
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:
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");
精彩评论