简体   繁体   English

Spring MVC Bean 更新(再次执行 bean)

[英]Spring MVC Bean Update (Execute the bean again)

So I'm new with Spring MVC and I need to update a bean after determined action.所以我是 Spring MVC 的新手,我需要在确定的操作后更新一个 bean。

Example: I defined the following bean:示例:我定义了以下 bean:

@Bean
public LocaleResolver localeResolver(){
    CookieLocaleResolver resolver = new CookieLocaleResolver();
    resolver.setDefaultLocale(new Locale("en"));
    return resolver;
}

After the user do the login in the system, I need to update the bean to match the language set up in his profile.用户登录系统后,我需要更新 bean 以匹配他的配置文件中设置的语言。 So, how can I call (execute) the bean again after the login?那么,登录后如何再次调用(执行)bean? Thanks.谢谢。

This is not aa standard way to do handle the user's locale.这不是处理用户语言环境的标准方法。 I recommend storing this information in the database with the user itself as long as the characteristic is mutable and varies across multiple users.我建议将此信息与用户本身一起存储在数据库中,只要该特征是可变的并且在多个用户之间变化。

However, one of the best ways of updating bean in runtime is using DefaultSingletonBeanRegistry which is still supported in the current version of Spring (5.2.x as far as I know).但是,在运行时更新 bean 的最佳方法之一是使用DefaultSingletonBeanRegistry ,当前版本的 Spring(据我所知为 5.2.x)仍然支持它。 Actually, what you do is to delete the bean and register it back again with a new value.实际上,您所做的是删除 bean 并使用新值重新注册它。

Start with ConfigurableApplicationContext that helps you to get the DefaultSingletonBeanRegistry .从可帮助您获取DefaultSingletonBeanRegistryConfigurableApplicationContext开始。

@Autowired
ConfigurableApplicationContext context;

And the code of deletion and registration of a bean should look like:一个bean的删除和注册代码应该是这样的:

LocaleResolver localeResolver = ... // a new bean to be registered, up to you :)

DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) context.getBeanFactory();
registry.destroySingleton("localeResolver");
registry.registerSingleton("localeResolver", localeResolver);

I have never used it actually, but I have found a few examples that might be useful: Programcreek .我实际上从未使用过它,但我发现了一些可能有用的示例: Programcreek

Important: I am worried this way will not update/refresh already registered old injected beans.重要提示:我担心这种方式不会更新/刷新已经注册的旧注入 bean。 I hope someone can confirm/dispute this statement.我希望有人可以确认/反驳这一说法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM