编辑 通过更改包修复。
我有这个spring框架的配置文件
@Configuration
public class AppConfig {
@Bean(initMethod = "populateCache")
public AccountRepository accountRepository(){
return new JdbcAccountRepository();
}
}
JdbcAccountRepository 看起来像这样。
@Repository
public class JdbcAccountRepository implements AccountRepository {
@Override
public Account findByAccountId(long
return new SavingAccount();
}
public void populateCache() {
System.out.println("Populating Cache");
}
public void clearCache(){
System.out.println("Clearing Cache");
}
}
我是 spring 框架的新手,正在尝试使用 initMethod 或 destroyMethod。这两种方法都显示以下错误。
Caused by: org.springframework.beans.factory.support.BeanDefinitionValidationException: Could not find an init method named 'populateCache' on bean with name 'accountRepository'
这是我的主要方法。
public class BeanLifeCycleDemo {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = new
AnnotationConfigApplicationContext(AppConfig.class);
AccountRepository bean = applicationContext.getBean(AccountRepository.class);
applicationContext.close();
}
}
编辑 我正在练习一本书,并为不同的章节创建了许多包。错误是它从没有该方法的不同包导入不同的 JdbcAccountRepository。我修好了,现在可以用了。我从答案中得到了暗示。
最佳答案
如您所说,如果您混合配置类型,可能会造成混淆。此外,即使您创建了一个 AccountRepository
类型的 Bean,因为 Spring 在运行时做了很多事情,它可以调用您的 initMethod,即使编译器不能。
所以是的,如果您有许多相同类型的 bean,Spring 可能会混淆并知道要调用哪个 bean,因此您会出现异常。
哦,顺便说一下,有一个 Configuration
创建 accountRepoisitory
Bean
,你可以删除 @Repository
从你的 JdbcAccountRepository
... 它是 @Configuration + @Bean
或 @Component/Repository/Service + @ComponentScan
。
长话短说
这里有更多信息以及 Spring 如何创建您的 bean:Spring 注入(inject)了什么对象?
@Bean(initMethod = "populateCache")
public AccountRepository accountRepository(){
return new JdbcAccountRepository();
}
使用这段代码,Spring 将:
- 检测到您要在应用程序上下文中添加一个 Bean
- 从方法签名中检索 bean 信息。在您的情况下,它将创建一个名为
accountRepository
的AccountRepository
类型的 bean...这就是 Spring 所知道的,它不会查看您的方法主体。 - 一旦 Spring 分析完您的类路径或扫描 bean 定义,它将开始实例化您的对象。
- 它将因此创建类型为
AccountRepository
的 beanaccountRepository
。 - 但是 Spring 很“聪明”,对我们很好。即使您无法在没有编译器对您大喊大叫的情况下编写此代码,Spring 仍然可以调用您的方法。
为了确定,请尝试编写以下代码:
AccountRepository accountRepository = new JdbcAccountRepository();
accountRepository.populateCache(); // Compiler error => the method is not found.
但它适用于 Spring...Magic。
我的建议,但你现在可能也有同样的想法:如果你有跨多个包的类来回答不同的业务案例,那么依赖于 @Configuration
类。 @ComponentScan
非常适合启动您的开发,但是当您的应用程序增长时会达到极限...
关于java - 为什么 @Bean(initMethod ="") 在 spring 中没有检测到给定的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60070750/