Spring Tips, Common Problems and their Solutions


This posts shares the common spring problems and their solution. I am writing down these to help you and myself to keep it indexed for future reference. Please share in comments, if you want to add one.




  1. How to pass the dependency in super class. For example I am having an abstract class AbsClass and its subclass SubClass. As you can see AbsClass requires DataBundle bean and we may need to inject it from SubClass.

    public abstract class AbsClass {
    
        private DataBundle dataBean;
    
        public AbsClass(DataBundle dataBean) {
            this.dataBean = dataBean;
        }
    
        public void add(Data data) {
            DataBundle.store(data);
        }
    }
    
    public class SubClass extends AbsClass {
    
        private DataBundle dataBean;
    
        @Autowired
        public AbsClass(DataBundle dataBean) {
            super(dataBean);
            this.dataBean = dataBean;
        }
    
        public void update(Data data) {
            DataBundle.update(data.getId(), data);
        }
    }
    I have used here @Autowired annotation. You can also use @Inject.
  2. Why my RestController/Bean/etc. is not getting read/detected by the Spring?
    This happens, when your Java class resides in the code which is not scanned by Spring. For e.g. in Spring Boot if you have given the main App java class path in configuration (com.sample.app.MainClass) then it will scan only those package which are either in that package or sub-package (com.sample.app.*). Thats the reason Controller which is in com.controllers.sampleapp would not be scanned and would not be available.



Do you enjoy this article? please help spread the word.
Your views are valuable. Post your view