Injecting property using @Value to abstract class

前端 未结 2 2061
再見小時候
再見小時候 2021-02-07 23:09

I have an abstract class in which I am trying to use the @Value annotation to inject value from a property file

public abstract class Parent {
     @Value (\"${s         


        
2条回答
  •  梦谈多话
    2021-02-07 23:34

    Can I inject value into abstract class this way?

    Abstract classes cannot be instantiated, so nothing can be injected into the abstract class. Instead , you should inject the value to its concrete subclass.

    Make sure your concrete subclass is marked as @Component stereotype and being "component scanning" by Spring . @Component on the abstract class is not needed as it cannot be instantiated.


    Update : I finally figure out that you are trying to access the injected value inside the constructor but found that the value is not set. It is because Spring will inject the value after the bean is instantiated . So if constructor injection is not used , the injected value cannot be accessed inside the constructor . You can use @PostContruct or implementing InitializingBean as suggested by Matt.

    Following shows if XML configuration is used :

    
    
    
    
        
    
    
    
    
    

    Perform your common action using sharedVal inside Parent#postConstruct()

提交回复
热议问题