gpt4 book ai didi

java - Spring表达式语言: @Bean cannot find itself

转载 作者:行者123 更新时间:2023-12-02 10:52:38 25 4
gpt4 key购买 nike

在我的类 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 解析将在 Autowiring 之后的运行时期间发生,并且在没有 bean 存在的情况下不可能调用 getByIsbn() 方法。即使我在配置中显式声明一个 bean,例如:

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

我收到同样的错误。

如果有人可以向我解释这种行为,我将非常感激。

我有以下类(class):

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 中找到了做我想做的事情的正确方法。我将条件更改为

条件=“#root.target.useCache()”

感谢所有回答的人。

关于java - Spring表达式语言: @Bean cannot find itself,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52044710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com