Spring 表达式语言:@Bean 找不到自己

Spring Expression Language: @Bean cannot find itself

在我的 class SimpleBookRepository 中,我试图从 Spring 的 @Cacheable 注释中访问实例方法以确定我是否应该使用缓存。当我尝试 运行 应用程序时,它无法启动并告诉我:

Description:

A component required a bean named 'SimpleBookRepository' that could not be found.

Action:

Consider defining a bean named 'SimpleBookRepository' in your configuration.

这让我很困惑,因为当我删除条件 = "@SimpleBookRepository.useCache()" 位时,应用程序 运行 完全正常。我认为条件评估和 bean 解析将在自动装配后的 运行 时间内发生,并且如果 bean 不存在就不可能调用 getByIsbn() 方法。即使我确实在配置中明确声明了一个 bean,如:

@Bean
public SimpleBookRepository simpleBookRepository(){
    return new SimpleBookRepository();
}

我收到同样的错误。

如果有人能向我解释这种行为,我将不胜感激。

我有以下 classes:

SimpleBookRepository.java

package com.mycompany.app;

@Component
public class SimpleBookRepository implements BookRepository{

    @Value("${cache.use}")
    private boolean useCache;

    public boolean useCache(){
        return useCache;
    }

    @Override
    @Cacheable(cacheNames="books", condition = "@SimpleBookRepository.useCache()")
    public Book getByIsbn(String isbn){
        //Get mock data
    }

}

Application.java

package com.mycompany.app;

@SpringBootApplication
@EnableCaching
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }

}

CachingConfiguration.java

package com.mycompany.app;

@EnableCaching
@EnableAutoConfiguration
@Configuration
public class CachingConfiguration {
    //Configure CacheManager bean
}

AppRunner.java

package com.mycompany.app;

@Component
public class AppRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(AppRunner.class);
    private final BookService bookService;

    @Autowired
    public AppRunner(BookService bookService){
        this.bookService = bookService;
    }

    @Override
    public void run(String... args) throws Exception{
        getBooks();

    }
}

BookService.java

package com.mycompany.app;

@Service
public class BookService {

    private BookRepository bookRepository;

    @Autowired
    public BookService(BookRepository bookRepository){
        this.bookRepository = bookRepository;
    }

    public Book getByIsbn(String isbn){
        return bookRepository.getByIsbn(isbn);
    }

}

BookRepository.java

package com.mycompany.app

@Component
public interface BookRepository {

    Book getByIsbn(String isbn);

}

我实际上只是找到了在 SpEL 中做我想做的事情的正确方法。我将条件更改为

condition = "#root.target.useCache()"

感谢所有回答的人。