Java 8添加了一个新功能,通过它我们可以在接口中提供方法实现。在Spring 4中是否有任何方法可以在接口中注入bean,可以在方法体内使用?下面是示例代码
public interface TestWiring{
@Autowired
public Service service;// this is not possible as it would be static.
//Is there any way I can inject any service bean which can be used inside testWiringMethod.
default void testWiringMethod(){
// Call method of service
service.testService();
}
}
这有点棘手但如果您需要接口内部的依赖性以满足任何要求,它就可以工作。
我们的想法是声明一个方法,该方法将强制实现的类提供您想要自动装配的依赖关系。
这种方法的不好的一面是,如果你想提供太多的依赖项,代码将不会很漂亮,因为每个依赖项需要一个getter。
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;
}
}
您可以创建应用程序上下文的Class utils,并在任何地方使用它,即使不是bean类。
你可以使用以下代码:
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) {
ApplicationContextUtil.applicationContext = context;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
并将其添加到您的弹簧配置中
<bean class="com.example.ApplicationContextUtil" id="applicationContextUtil"/>
现在在您需要时使用简单:
ApplicationContextUtil.getApplicationContext().getBean(SampleBean.class)
这个词在网络和简单的春季应用程序。