我对 Spring 比较陌生,甚至对注释和自动装配也比较陌生。我不知道如何连接我的豆子。这个想法是通过更改 application-config.xml 在 CacheService 和 NoCacheService 之间切换,但我无法克服异常。
例外
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Service' defined in ServletContext resource [/WEB-INF/application-config.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [webapp.Services]: Specified class is an interface
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
<snip>
课程:
package webapp;
interface Service {
List<String> get();
}
@Service("cache")
CacheService implements Service {
//from cache then from IO bound source
@Autowired
public CacheService(int v1, int v2)
...
}
@Service("nocache")
NoCacheService implements Service {
//from IO bound source
....
}
控制器:
@RequestMapping("/")
@Controller
public class ServiceController {
@Autowired
Service service;
...
}
应用程序配置 xml:
<mvc:annotation-driven />
<context:component-scan base-package="webapp"/>
<beans:bean id="Service" class="webapp.Service">
<beans:property name="cache" ref="cache" />
</beans:bean>
<beans:bean id="cache" class="webapp.CacheService">
<beans:constructor-arg index="0" value="50"/> <!-- v1 -->
<beans:constructor-arg index="1" value="100"/> <!-- v2 -->
</beans:bean>
<beans:bean id="nocache" class="webapp.NoCacheService">
</beans:bean>