1. 程式人生 > >springboot的service無法注入,不能有static程式碼

springboot的service無法注入,不能有static程式碼

springboot專案中,一個service無法注入,嘗試了很多方法,均無效。最後發現是因為裡面加了靜態的程式碼,長這個樣子:


@Service
public class XXXService{
    
    //······

    static{
        // 做了一些靜態的初始化工作
    }
}

時間緊,沒有深入瞭解原因。

回去仔細一看,其實報錯資訊裡面提示了出錯原因:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'XXXController': Unsatisfied dependency expressed through field 'XXXService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'XXXService' defined in file [···\service\XXXService.class]: Invocation of init method failed; nested exception is java.lang.NoSuchFieldError: Shared