我试图注入一个bean到控制器,但看起来像Spring没有使用bean.xml文件。春 - 通过参数注入对象
下面是代码:
控制器
@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;
}
}
如果我注释MyEve带有@Service的ntService Spring试图将它注入到Controller中,但是抱怨没有提供baseURL(没有提供'java.lang.String'类型的限定bean)。所以,我创建了一个bean.xml文件在src /主/资源
<?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抱怨找不到了eventService的bean。
我错过了什么吗?
我已经试图与自动装配Autowired,但春说,它无法找到eventService的bean。我得到它(几乎)工作的唯一方法是使用Service注释MyEventService:在这种情况下,问题与baseURL有关。在以前的项目中,我将所有的bean定义在一个xml文件中,并且没有注释,并且它工作正常。 – algiogia