programing

스프링 부트에서 조건부로 오토와이어를 사용하는 방법은 무엇입니까?

lovejava 2023. 7. 8. 10:25

스프링 부트에서 조건부로 오토와이어를 사용하는 방법은 무엇입니까?

스케줄러 클래스를 하나 만들었습니다.

public class TestSchedulderNew {

@Scheduled(fixedDelay = 3000)
public void fixedRateJob1() {
System.out.println("Job 1 running");
}

@Scheduled(fixedDelay = 3000)
public void fixedRateJob2() {
System.out.println("Job 2 running");
}
}

구성에서 조건부 목적으로 이를 활성화하기 위해 @ConditionalOnProperty 주석을 추가했습니다.

 @Bean
@ConditionalOnProperty(value = "jobs.enabled")
public TestSchedulderNew testSchedulderNew() {
return new TestSchedulderNew();
}

이제 컨트롤러에서 저는 스케줄러를 중지하기 위해 "stopScheduler" 메서드를 만들었습니다. 이 컨트롤러에서 저는 TestSchedulerNew 클래스를 자동 배선했습니다.

 @RestController
 @RequestMapping("/api")
 public class TestCont {

private static final String SCHEDULED_TASKS = "testSchedulderNew";

 @Autowired
 private ScheduledAnnotationBeanPostProcessor postProcessor;    /]

 @Autowired
 private TestSchedulderNew testSchedulderNew;


 @GetMapping(value = "/stopScheduler")
 public String stopSchedule(){
  postProcessor.postProcessBeforeDestruction(testSchedulderNew, 
   SCHEDULED_TASKS);
  return "OK";
  }
 }     

이제 문제는 조건부 속성이 거짓이면 예외 이하가 된다는 것입니다.

   Field testSchedulderNew in com.sbill.app.web.rest.TestCont required a bean of type 'com.sbill.app.schedulerJob.TestSchedulderNew

정말로 모든 게 잘 되면,

우리가 이것을 해결할 방법이 있습니까?

사용할 수 있습니다.@Autowired(required=false)및 null 체크인stopScheduler방법.

 @Autowired(required=false)
 private TestSchedulderNew testSchedulderNew;

 @GetMapping(value = "/stopScheduler")
 public String stopSchedule() {
     if (testSchedulderNew != null) {
         postProcessor.postProcessBeforeDestruction(testSchedulderNew, 
          SCHEDULED_TASKS);
         return "OK";
     }
     return "NOT_OK";
 }

언급URL : https://stackoverflow.com/questions/57656119/how-to-autowire-conditionally-in-spring-boot