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 used inside the method body? Below is the sample code
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(); } }
If you try to use @Autowired on an interface, the Spring framework would throw an exception as it won't be able to decide which implementation class to use.
@Autowired in Spring Boot. In a Spring Boot application, auto-wiring is enabled by default.
You can use @Autowired annotation on setter methods to get rid of the <property> element in XML configuration file. When Spring finds an @Autowired annotation used with setter methods, it tries to perform byType autowiring on the method.
@Bean is just for the metadata definition to create the bean(equivalent to tag). @Autowired is to inject the dependancy into a bean(equivalent to ref XML tag/attribute).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With