簡體   English   中英

春季表達語言:@Bean找不到自己

[英]Spring Expression Language: @Bean cannot find itself

在我的類SimpleBookRepository中,我試圖從Spring的@Cacheable批注中訪問一個實例方法,以確定是否應該使用緩存。 當我嘗試運行該應用程序時,它無法啟動並告訴我:

描述:

一個組件需要找不到名為“ SimpleBookRepository”的bean。

行動:

考慮在配置中定義一個名為“ SimpleBookRepository”的bean。

這讓我很困惑,因為當我刪除condition =“ @ 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);

}

我實際上只是在SpEL中找到了執行我想要的操作的正確方法。 我將條件更改為

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

感謝所有回答。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM