当通过注释驱动配置spring时,如何为bean设置init-method?

Cha*_*les 14 configuration spring annotations initialization spring-roo

我使用spring roo来构建项目并且它是注释驱动的,并且XML文件中没有bean定义.所有配置信息都在*.aj文件中.

现在我想为没有默认构造函数的bean设置一个init方法(该bean来自第三方,它有一个带参数的构造函数,我不能删除它们或给它一个默认的构造函数. )

有谁能告诉我怎么做,拜托?

我想这样做的原因是因为我想applicationContext.getBean("thatBeanName")用来动态获取bean并使用它.因为bean没有默认构造函数,所以我总是得到错误:java.lang.NoSuchMethodException: com.to.that.bean.<init>()这就是我想将init方法添加到bean的原因.

Ara*_*ram 24

使用@PostConstruct如下例所示.它相当于init-method="initialize()"

@PostConstruct
public void initialize() {
    messages.put("English", "Welcome");
    messages.put("Deutsch", "Willkommen");
}
Run Code Online (Sandbox Code Playgroud)

  • 它不等同于IMHO @Bean(initMethod ="init")是正确的,如果可能的话我会避免使用@PostConstruct作为initMethod. (3认同)

Bre*_*ntR 20

@Bean(initMethod="init")
public MyBean getMyBean() {
 ...
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您无权访问要创建的Bean的源,请使用它。否则,请使用@PostConstruct。 (2认同)

mag*_*lla 5

在 spring 容器中,最后调用的是“init”方法,
@postconstruct 在 afterPropertiesSet 之前调用。所以如果有人错过使用会更安全。“为同一个bean配置的多个生命周期机制,具有不同的初始化方法,调用如下:

1.方法注解@PostConstruct

2.afterPropertiesSet() 由 InitializingBean 回调接口定义

  1. 自定义配置的 init() 方法 [ https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-java-lifecycle-callbacks][1]

虽然,今天我更喜欢独立于 Spring 并使用 @Postconstract,甚至配置默认的 init 方法识别。只有有意义的方法名称表明它应该用于初始化 - 从框架中清除,从注释中清除。