需要建议以修复控制器中的自动配线问题

5sxhfpxr  于 2022-09-18  发布在  Spring
关注(0)|答案(1)|浏览(144)

在我们的Spring应用程序中,我们有一个控制器,cron作业会调用它来进行健康检查

因为我们正在迁移过程中,所以我们将禁用作为新平台的Spring配置文件p2的某些Spring Bean,而只为旧配置文件p1创建它们

目前,如果我们在新平台上构建我们的应用程序,我们会收到以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'some.name.of.controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private [ bean that is disabled in p2 ] bean that is disabled in p2 ; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ bean that is disabled in p2 ] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
@Controller("some.name.of.controller")
@RequestMapping("/somePath")
public class someHealthCheckController {

// the SecretObject will not be available for spring profile "p2" which only gets created in profile "p1"
@Autowired
private SecretObject secretObject

我尝试将这个自动连接的行提取到一个新的Java类中,并让控制器创建该类的一个示例并调用该方法,但它不起作用。

正在寻找解决此问题的建议,谢谢!

ltskdhd1

ltskdhd11#

如果您的p2配置文件中不存在askObject,则依赖项是可选的,因此您必须使用@Autowired(required=false)对其进行注解,并在使用它之前检查askObject是否为空(p2配置文件)或不是(p1配置文件)。对于@Autowiredrequired的默认值为true

@Controller("some.name.of.controller")
@RequestMapping("/somePath")
public class someHealthCheckController {

// the SecretObject will not be available (null) for spring profile "p2" which only gets created in profile "p1"
@Autowired(required=false)
private SecretObject secretObject

相关问题