Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
975 views
in Technique[技术] by (71.8m points)

java - How to Reload/Re-init Bean in Spring boot?

I have email config class like this.

@Configuration
public class EmailConfiguration {

    @Autowired
    private ConfigService configService;


    @Bean
    public JavaMailSender JavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(configService.emailHost());
        mailSender.setPort(configService.emailPort());
        mailSender.setUsername(configService.emailAddress());
        mailSender.setPassword(configService.emailPassword());

        return mailSender;
    }
}

how to make this bean change the value at runtime every ConfigService was refreshed? I was refresh the ConfigService but the bean's value did not change.

question from:https://stackoverflow.com/questions/65713073/how-to-reload-re-init-bean-in-spring-boot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have three options to update singleton bean in spring context, you can chose one suitable for your use case:

Reload method In the Bean Create a method in your bean which will update/reload its properties. Based on your trigger, access the bean from spring context, and then call the reload method to update bean properties (since singleton) it will also be updated in spring context & everywhere it is autowired/injected.

Delete & Register Bean in Registry You can use DefaultSingletonBeanRegistry to remove & re-register your bean. The only drawback to this, it will not refresh/reload old instance of already autowired/injected bean in consumer classes.

DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) context.getBeanFactory();
registry.destroySingleton({yourbean}) //destroys the bean object
registry.registerSingleton({yourbeanname}, {newbeanobject}) //add to singleton beans cache

@RefreshScope Useful for refreshing bean value properties from config changes. But it has very limited & specific purpose. Resource to read more about it.

Let me know if this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...