spring 当spring由注解驱动配置时,如何为bean设置init-method?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8622369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:50:16  来源:igfitidea点击:

How to set up init-method for a bean when spring is configured by annotation driven?

springconfigurationannotationsinitializationspring-roo

提问by Charles

I use spring roo to build project and it's annotation driven, and there is no bean definition in XML file. All the configuration info is in *.aj file.

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

And now I want to set up an init method for a bean which don't have a default constructor (that bean is from the third party and it has a constructor with arguments, and I cannot remove them or give a default constructor to it.)

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

Is there anyone who can tell me how to do this, please?

有没有人可以告诉我如何做到这一点?

The reason I want to do this is because I want to use applicationContext.getBean("thatBeanName")to dynamically get the bean and use it. Because the bean don't have a default constructor, I always get the error: java.lang.NoSuchMethodException: com.to.that.bean.<init>()and this is why I want to add the init-method to the bean.

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

回答by Aravind Yarram

Use @PostConstructas shown in below example. It is equivalent to init-method="initialize()"

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

@PostConstruct
public void initialize() {
    messages.put("English", "Welcome");
    messages.put("Deutsch", "Willkommen");
}

回答by BrentR

@Bean(initMethod="init")
public MyBean getMyBean() {
 ...
}

回答by magulla

In spring container it is "init" method that being called the last,
@postconstruct called before afterPropertiesSet. so it is safer if someone miss use. "Multiple lifecycle mechanisms configured for the same bean, with different initialization methods, are called as follows:

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

1.Methods annotated with @PostConstruct

2.afterPropertiesSet() as defined by the InitializingBean callback interface

  1. A custom configured init() method [https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-java-lifecycle-callbacks][1]

1.方法注解@PostConstruct

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

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

Although, today I would prefer to be more Spring independent and use either @Postconstract, or even configure default init method recognition. to have only meaningful method name indicate that it should be used for initialization - clear from frameworks, clear from annotations.

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

回答by Aravind A

As @Pangea has put in , @PostConstructis the best choice. You could also implement initializingBean and do the initialization in afterPropertiesSet method .Check herefor this approach.

作为@Pangea已实施,@PostConstruct是最好的选择。您还可以实现 initializingBean 并在 afterPropertiesSet 方法中进行初始化。请在此处查看此方法。

回答by cinqS

I realized that there have been multiple answers trying to solve the problem. But with the newlyintroduced @Configurationwhich is popularly used within Spring Boot. Things are changed a little bit.

我意识到有多个答案试图解决这个问题。但是随着引入的@ConfigurationSpring Boot 中广泛使用。事情发生了一些变化。

If you are using @Beanannotation in @Configurationannotated class like:

如果您@Bean在带@Configuration注释的类中使用注释,例如:

@Configuration
class FooClass {
    @Bean
    public Bar bar() {
        return new Bar();
    }
}

If you want to use an automatically called method on the bean instance during initialization, you have two options below:

如果要在初始化期间在 bean 实例上使用自动调用的方法,则有以下两种选择:

Option1:

选项1:

@Configuration
class FooClass {
    @Bean(initMethod="init")
    public Bar bar() {
        return new Bar();
    }
}

Option2:

选项2:

@Configuration
class FooClass {
    @Bean
    public Bar bar() {
        Bar bar = new Bar();
        bar.init();
        return bar;
    }
}

BUT, as is explain in @BeanJava Doc here:

但是,正如@Bean这里的 Java Doc 中所解释的:

 /**

     * The optional name of a method to call on the bean instance during initialization.

     * Not commonly used, given that the method may be called programmatically directly

     * within the body of a Bean-annotated method.

     * The default value is {@code ""}, indicating no init method to be called.

     */

The second is regarded as a better answer. See link here

第二个被认为是更好的答案。在这里查看链接