有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java spring将参数传递到注入对象

我试图将一个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;
  }
}

如果我用@Service注释MyEventService,Spring会尝试将其注入控制器,但会抱怨没有提供baseURL(没有“java.lang.String”类型的合格bean可用)。所以我创造了一个豆子。src/main/resources下的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

我错过什么了吗


共 (2) 个答案

  1. # 1 楼答案

    您的尝试有两个问题

    1. xml bean定义未被提取的原因是您没有在控制器中注入服务,因为您正在为控制器使用注释,所以您需要告诉控制器需要如何注入服务,要解决这个问题,只需自动连接您的服务即可

      @RestController
      public class AppController {
      
      @Autowired
      private final EventService eventService;
      
      
      }
      
    2. 当您使用注释来构造基于arg的Springbean时,您还需要设置值,就像您在xml中所做的那样

      public class MyEventService {
      
      private final String baseURL;
      
      public MyEventService(@Value("#{your value here")String baseURL){
           this.baseURL = baseURL;
       }
      }
      
  2. # 2 楼答案

    Spring引导严重依赖于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中。性质

    baseURL=https://baseUrl
    

    然后

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

    @Autowired将告诉Spring引导查看您用@Component、@Service、@Repository、@Controller等声明的组件

    为了注入类别,我建议您声明一个CategoriesService(带有@Service),从配置文件中获取类别,或者在CategoriesService类中硬编码它们(用于原型设计)