Java 8 and Spring 4 : Use autowiring in interface

后端 未结 2 1510
心在旅途
心在旅途 2021-02-02 12:14

Java 8 added a new feature by which we can provide method implementation in interfaces. Is there any way in Spring 4 by which we can inject beans in the interface which can be u

2条回答
  •  囚心锁ツ
    2021-02-02 12:47

    You can created Class utils of application context and use it everywhere even not bean class .

    you can have code somethins this :

    public class ApplicationContextUtil implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext context) {
            ApplicationContextUtil.applicationContext = context;
        }
    
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
    }
    

    and add this to your spring configuration

    
    

    now simple to use when you need :

    ApplicationContextUtil.getApplicationContext().getBean(SampleBean.class)
    

    this word in web and simple spring app.

提交回复
热议问题