相关疑难解决方法(0)

Spring @Autowired - 实例化新bean

需要一些Spring自动装配和范围的帮助.

这是基本的app结构:

  1. 我有一个CustomHttpClient,注释为@Component,还从application.properties文件中提取一些与配置相关的属性(通过@Value注释).

  2. CustomHttpClient由我的应用程序中的多个服务使用.每当我使用CustomHttpClient时,我通过以下方式自动装配该实例:

    @Autowired
    private CustomHttpClient httpClient;
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我使用拦截器来修改CustomHttpClient中的一些变量,如下所示:

    public class MyInterceptor extends HandlerInterceptorAdapter {
    @Autowired CustomHttpClient httpClient;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    httpClient.setSomeProperty(newValue);
    ...
    
    Run Code Online (Sandbox Code Playgroud)

现在,这是问题所在.如果我按照上面的描述设置了所有内容,那么每当我通过拦截器更改CustomHttpClient的任何设置时,只要VM正在运行,就会为所有其他客户端保留该新值.因此,当我运行httpClient.setSomeProperty()时 - 该设置现在已永久保存.即使我从另一个客户端连接到该应用程序.

基本上我需要的是两件事:

  1. 仍然能够通过拦截器覆盖CustomHttpClient的默认设置(请求拦截器,通过配置).
  2. 确保为每个请求创建一个新的CustomHttpClient实例(在拦截器执行其魔法之后).

我尝试将CustomHttpClient的范围更改为@Scope("prototype"),但这样我就无法再使用拦截器更改CustomHttpClient的设置.

java spring spring-mvc autowired

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

autowired ×1

java ×1

spring ×1

spring-mvc ×1