1

I have one Base Abstract Class say A, which is being extended by another abstract class B and finally one concrete class C extending B.

Here in Class C trying to get the dataSource autowired in Base Abract Class A. But @Autowired is not Working in Abstract Class and even getting null in sop(dataSource)

If i autowire dataSource in concrete Class C, its working.

Please any one help me on this.. I want to use a common base class for getting dataSource. But @Autowired is not working in it.

Will be of great help if someone give a solution with example.

Thanks in Advance..

Sample Code:

 abstract Class A
        {
    @Autowired DataSource dataSource;

    setConnection(){ sop(dataSource); }

        }
    abstract Class B extends A
        { -- Method conn()
    { setConnection();}
        }
    Class C extends B
    {
    Invoke conn();
    }
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
user3615185
  • 55
  • 1
  • 8
  • Did you define your base package scan in spring config ? – sashok_bg Feb 02 '16 at 15:57
  • Post some actual code instead of pseudo code. It insn't clear where the `conn()` method is invoked nor how you are actually creating instances. Basically an `@Autowired` field cannot be null, unless you invoke methods in the constructor then fields aren't set OR when you are creating new instances yourself (those are outside the control of Spring and will not be injected). Also if you are using Spring I suggest using a `JdbcTemplate` instead of hacking away and managing connections yourself. – M. Deinum Feb 03 '16 at 07:00

2 Answers2

2

This should work assuming you've got all the abstract classes in the ComponentScan path. See: Spring can you autowire inside an abstract class?

Though I question if it's truly necessary to have an abstract class simply for setting the DataSource. Spring Beans are by default Singletons, so you'll get the same instance everywhere if you simply @Autowired the datasource into all of the "subclasses" directly.

Community
  • 1
  • 1
Ben M
  • 1,833
  • 1
  • 15
  • 24
0

What you're trying to do should work without any problem. As @Ben says in his answer, all parent classes should be scanned by Spring.

Besides, autowiring occurs after object creation. This means that if you are calling your C.conn() method from within your C class' constructor, the dataSource field will still be unset (i.e. its value will still be null).

If I were you, I'd check if the above conditions are met.

fps
  • 33,623
  • 8
  • 55
  • 110