2017-06-12 25 views
1

我试图注入一个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。

我错过了什么吗?

回答

0

Spring Boot很大程度上依赖于Java配置。

检查the docs如何申报@Component,@Service等

你的情况:

@Service 
public class MyEventService implements EventService { 

    private final String baseURL; 

    @Autowired 
    public MyEventService(Environment env){ 
    this.baseURL = env.getProperty("baseURL"); 
    } 
} 

而且在你/src/main/resources/application.properties

baseURL=https://baseUrl 

然后

​​

@Autowired会告诉Spring Boot查看你使用@Component,@Service,@Repository,@Controller等声明的组件。

要注入类别,我真的建议你声明一个CategoriesService(使用@Service)从配置文件中获取类别,或者只在类别服务类中对其进行硬编码(用于原型设计)。

0

有2个问题与你正在尝试

  1. 你的XML bean定义不拿起原因是因为你没有在你控制注射服务,因为你正在使用注解为您控制器,你需要告诉你控制器的服务需要如何注入,来解决这个刚刚当您正在使用的注释,你需要的设定值,以及基于结构 - 精氨酸的Spring bean自动装配服务

    @RestController 
    public class AppController { 
    
    @Autowired 
    private final EventService eventService; 
    
    
    } 
    
  2. ,就像你在做什么一样在你的XML。

    public class MyEventService { 
    
    private final String baseURL; 
    
    public MyEventService(@Value("#{your value here")String baseURL){ 
        this.baseURL = baseURL; 
    } 
    } 
    
+0

我已经试图与自动装配Autowired,但春说,它无法找到eventService的bean。我得到它(几乎)工作的唯一方法是使用Service注释MyEventService:在这种情况下,问题与baseURL有关。在以前的项目中,我将所有的bean定义在一个xml文件中,并且没有注释,并且它工作正常。 – algiogia