为什么@Bean(initMethod="") 在 spring 中没有检测到给定的方法?

Ksh*_*kal 2 java spring

通过更改包来编辑固定。

我有 spring 框架的这个配置文件

@Configuration
public class AppConfig {
   @Bean(initMethod = "populateCache")
    public AccountRepository accountRepository(){
       return new JdbcAccountRepository();
   }
}
Run Code Online (Sandbox Code Playgroud)

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我是 spring 框架的新手,并尝试使用 initMethod 或 destroyMethod。这两种方法都显示以下错误。

Caused by: org.springframework.beans.factory.support.BeanDefinitionValidationException: Could not find an init method named 'populateCache' on bean with name 'accountRepository'
Run Code Online (Sandbox Code Playgroud)

这是我的主要方法。

public class BeanLifeCycleDemo {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = new
                AnnotationConfigApplicationContext(AppConfig.class);
        AccountRepository bean = applicationContext.getBean(AccountRepository.class);
        applicationContext.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 我正在练习一本书,并为不同的章节创建了许多包。错误是它从没有该方法的不同包中导入了不同的 JdbcAccountRepository。我修复了它,现在可以使用了。我从答案中得到了暗示。

RUA*_*ult 5

就像你说的,如果你混合配置类型,它可能会令人困惑。此外,即使你创建了一个类型为 的 Bean AccountRepository,因为 Spring 在运行时做了很多事情,它可以调用你的 initMethod,即使编译器不能。

所以是的,如果您有许多相同类型的 bean,Spring 可能会混淆,不知道要调用哪个,因此您的例外。

哦,顺便说一句,Configuration创建了accountRepoisitory Bean,您可以@RepositoryJdbcAccountRepository...中删除。它是@Configuration + @Bean@Component/Repository/Service + @ComponentScan

TL; 博士

以下是更多信息以及 Spring 如何创建您的 bean:Spring 注入了什么对象?

@Bean(initMethod = "populateCache")
public AccountRepository accountRepository(){
    return new JdbcAccountRepository();
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,Spring 将:

  • 检测你要在应用Context中添加一个Bean
  • 从方法签名中检索 bean 信息。在您的情况下,它将创建一个AccountRepository名为accountRepository... 这就是 Spring 所知道的所有类型的 bean ,它不会查看您的方法主体。
  • 一旦 Spring 完成分析您的类路径或扫描 bean 定义,它将开始实例化您的对象。
  • 因此,它将创建您的 beanaccountRepository类型AccountRepository
  • 但是 Spring 很“聪明”,对我们很好。即使您无法在没有编译器对您大喊大叫的情况下编写此代码,Spring 仍然可以调用您的方法。

为了确保,请尝试编写以下代码:

AccountRepository accountRepository = new JdbcAccountRepository();
accountRepository.populateCache(); // Compiler error => the method is not found.
Run Code Online (Sandbox Code Playgroud)

但它适用于春天......魔术。

我的建议,但你现在可能会这么想:如果你有跨多个包的类来回答不同的业务案例,那么依赖@Configuration类。@ComponentScan非常适合启动您的开发,但是当您的应用程序增长时会达到极限...