以下是代码:
控制器:
@RestController
public class AppController {
private final EventService eventService;
private List<String> categories;
public AppController(final EventService eventService) {
this.eventService = eventService;
}
}
注入对象的接口
public interface EventService {
// some methods
}
它的实现
public class MyEventService {
private final String baseURL;
public MyEventService(String baseURL){
this.baseURL = baseURL;
}
}
如果我使用@Service为MyEventService添加注解,Spring将尝试将其注入到控制器中,但是会抱怨没有提供baseURL(没有可用的类型为'java.lang.String'的合格bean)。因此,我在src/main/resources下创建了一个bean.xml文件。
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="eventService" class="xyz.MyEventService">
<constructor-arg type="java.lang.String" value="fslkjgjbflgkj" />
</bean>
<bean id="categories" class="java.util.ArrayList">
<constructor-arg>
<list>
<value>music</value>
<value>comedy</value>
<value>food</value>
</list>
</constructor-arg>
</bean>
</beans>
但是如果我从MyEventService中删除@Service注释,似乎不起作用,Spring会抱怨找不到名为eventService的bean。我是否漏掉了什么?