Spring Annotation Lazy Load

时间:2016-11-12 06:02:47

标签: java spring dependency-injection spring-annotations spring-scheduled

Currently working on spring 3.2.3. We have developed one API application with this for 2 years now. It was working good. But as bean classes are increases there was exception about Circular dependency. So we have resolved that with changing default-lazy-init="true" in application-context.xml. But that lead to another challenge about @Scheduled is not working at all.

Note : Our application uses spring annotation so beans are not declared in xml file. Below is my code for reference :

applicationContext.xml

<beans default-lazy-init="true" xmlns="http://www.springframework.org/schema/beans">

Service class

@Service("notificationService")
public class NotificationService{

    @Scheduled(cron = "0 09 11 * * *")
    @Async
    public void sampleNotificaton(){

    }
}

Try to add @Lazy(false) at service level but circular dependency exception still occur.

Appreciate your suggestion. Thanks.

1 个答案:

答案 0 :(得分:1)

由于我们有限制不打破循环依赖(这通常很容易解决BTW),我会尝试技巧,调度注释将被提取到单独的bean中:

@Component
public class NotificationScheduler {
    @Autowired //I prefer contructor injection, but field injection might be needed in this case because or circular dependency 
    private NotificationService notificationService;

    @Scheduled(cron = "0 09 11 * * *")
    public void sampleScheduling() {
        notificationService.sampleNotification();
    }
}

@Service("notificationService")
public class NotificationService{

    @Async
    public void sampleNotificaton(){

    }
}