在Spring请求处理程序方法中创建原型范围的组件

问题描述 投票:0回答:2

我正在编写Spring应用程序,并在学习过程中学习Spring。到目前为止,每当我发现自己想要引用ApplicationContext时,这都意味着我正在尝试以错误的方式进行操作,因此我想我会先问清楚。

我需要为每个请求实例化一个原型bean:

@Component
@Scope("prototype")
class ComplexThing {
    @Autowired SomeDependency a
    @Autowired SomeOtherDependency b
    public ComplexThing() { }
    // ... complex behaviour ...
}

所以我尝试了这个:

@Controller
@RequestMapping ("/")
class MyController {
    @GetMapping
    public String index (ComplexThing complexThing, Model model) {
        model.addAttribute("thing", complexThing);
        return "index"
    }
}

而且我希望Spring为请求注入新的ComplexThing,就像它注入了Model一样。但是后来我发现正确的解释是调用者将在请求中发送ComplexThing。

我以为可以将Bean注入请求处理程序中,但是I don't see one here

因此,在这种情况下,我应该将控制器设置为ApplicationContextAwaregetBean吗?

java spring-mvc
2个回答
0
投票

我用ObjectProvider界面解决了:

@Controller
@RequestMapping ("/")
class MyController {
    @Autowired 
    ObjectProvider<ComplexThing> complexThingProvider;
    @GetMapping
    public String index (Model model) {
        model.addAttribute("thing", complexThingProvider.getObject());
        return "index"
    }
}

ObjectProvider的另一个好处是能够将一些参数传递给构造函数,这意味着我可以将某些字段标记为final

@Controller
@RequestMapping ("/")
class MyController {
    @Autowired 
    ObjectProvider<ComplexThing> complexThingProvider;
    @GetMapping
    public String index (String username, Model model) {
        model.addAttribute("thing", complexThingProvider.getObject(username));
        return "index"
    }
}
@Component
@Scope("prototype")
class ComplexThing {
    @Autowired SomeDependency a
    @Autowired SomeOtherDependency b
    final String username;
    public ComplexThing(String username) {
        this.username = username;
    }
    // ... complex behaviour ...
}

-1
投票

您的观点是正确的。无法将原型范围内的bean(实际上也是其他所有bean类型)直接注入到控制器请求处理程序中。我们只有4个选项。

  1. 在调用方中获取应用程序上下文,并在调用方法时传递Bean。 (但是在这种情况下,由于这是一个请求处理程序,因此这种方法是不可能的。)

  2. 使控制器类为ApplicationContextAware,通过重写setApplicationContext()方法来设置applicationContext对象,并使用它来获取bean的实例。

  3. 创建bean类型的私有变量,并用@Autowired对其进行注释。

  4. 创建bean类型的私有变量并用@Inject对其进行注释(@Autowired@Inject具有相同的功能。但是@Autowired是特定于Spring的。]]]

© www.soinside.com 2019 - 2024. All rights reserved.