java - spring - 将参数传递给注入(inject)的对象

标签 java spring-boot dependency-injection

我正在尝试将 bean 注入(inject)到 Controller 中,但看起来 Spring 没有使用 bean.xml 文件。

这是代码:

Controller

@RestController
public class AppController {

  private final EventService eventService;
  private List<String> categories;

  public AppController(final EventService eventService) {
    this.eventService = eventService;
  }
}

要注入(inject)的对象的接口(interface)

public interface EventService {
   // some methods
}

其实现

public class MyEventService {

  private final String baseURL;

  public MyEventService(String baseURL){
    this.baseURL = baseURL;
  }
}

如果我用@Service注释MyEventService,Spring会尝试将其注入(inject)到 Controller 中,但提示未提供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 一样。

我错过了什么吗?

最佳答案

Spring Boot 严重依赖 Java Config。

检查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

然后

@RestController
public class AppController {

  private final EventService eventService;

  @Autowired
  public AppController(final EventService eventService) {
    this.eventService = eventService;
  }
}

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

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

关于java - spring - 将参数传递给注入(inject)的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44505750/

相关文章:

java - 如何在 Android 上以编程方式自动接听来电

java - JCL 通过 SLF4j 登录 Glassfish

java - 最终属性@Value中的Spring属性注入(inject)-Java

java - 快速排序不起作用

Java字段猜测

java - Spring Boot 中 @oneToMany 双向映射的问题

Spring Boot SSL 客户端

java - 如何修复 "Direct notifications and query notifications cannot be requested together"

service - Angular 2 : Need to add provider in component for dependency on service?

generics - 传递 map 功能时类型推断不起作用