Java 8 and Spring 4 : Use autowiring in interface

你。 提交于 2019-12-02 20:42:52

This is a bit tricky but it works if you need the dependency inside the interface for whatever requirement.

The idea would be to declare a method that will force the implemented class to provide that dependency you want to autowire.

The bad side of this approach is that if you want to provide too many dependencies the code won't be pretty since you will need one getter for each dependency.

public interface TestWiring {

   public Service getService();

   default void testWiringMethod(){
       getService().testService();
   }

}


public class TestClass implements TestWiring {

    @Autowire private Service service;

    @Override
    public Service getService() {
        return service;
    }

}

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

<bean class="com.example.ApplicationContextUtil" id="applicationContextUtil"/>

now simple to use when you need :

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

this word in web and simple spring app.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!