在我的类SimpleBookRepository中,我试图从Spring的@Cacheable批注中访问一个实例方法,以确定是否应该使用缓存。当我尝试运行该应用程序时,它无法启动并告诉我:
说明:
一个组件需要一个找不到名为'SimpleBookRepository'的bean。
操作:
考虑在您的配置中定义一个名为“ SimpleBookRepository”的bean。
这让我很困惑,因为当我删除条件=“ @ SimpleBookRepository.useCache()”位时,应用程序运行得很好。我认为条件评估以及因此的bean解析将在自动装配后的运行时发生,并且在没有bean的情况下调用getByIsbn()方法是不可能的。即使我确实在配置中明确声明了一个bean,例如:
@Bean
public SimpleBookRepository simpleBookRepository(){
return new SimpleBookRepository();
}
我收到相同的错误。
如果有人可以向我解释这种行为,我将不胜感激。
我有以下课程:
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);
}
答案 0 :(得分:1)
我实际上只是在SpEL中找到了执行我想要的操作的正确方法。我将条件更改为
condition = "#root.target.useCache()"
感谢所有回答的人。