注入来自依赖项但没有@Bean注释的Spring bean

时间:2020-03-15 14:19:28

标签: spring spring-boot dependency-injection

我的Spring Boot应用有一个新的Zoo @Service类:

@RequiredArgsConstructor
@Service
public class Zoo{
    private final Cat cat;

我需要在构造函数中注入一个Cat类,该类是从我通过pom导入到项目的旧版库中获得的:

    <dependency>
        <groupId>com.example</groupId>
        <artifactId>animals</artifactId>
    </dependency>

package com.example.animals
class Cat{..}

我无法更改旧版animals包的代码,以向Cat类添加注释。

当我尝试运行该应用程序时,出现此错误:

com.example.zoo中构造函数的参数0需要一个类型为'com.example.animals.cat'的bean,

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

是的,您可以通过创建一个@Configuration类来解决此问题,在该类中定义一个代表Cat实例的Spring Bean,如以下示例所示。

@Configuration
public class AppConfiguration {

  @Bean
  public Cat cat() {
    return new Cat();
  }
}
相关问题