Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection for java 8 default interface methods

Tags:

java

spring

I have an interface that defines a setter/getter using java 8 default methods, but I am getting an error when attempting to wire it up in Spring. I really want to avoid using abstract class and I don't want to duplicate the code. Here is what I am doing:

public interface MyProcessor
{
  public static final WeakHashMap<Function1D, Integer> paramMap = new WeakHashMap<>();

  default void setParam(int param)
  {
        paramMap.put(this, param);
  }

  default int getParam()
  {
      return paramMap.get(this);
  } 

  default double doSomthingWithParam(double x)
  {  
          return doSomething() * getParam();
  } 

  double doSomething();
 }


public class MyProcessorImp extends SomeClass implements MyProcessor
{
    double doSomething() {....}
 } 

  <bean class="....MyProcessorImp"> <property name="param" value="3"/></bean>

Bean property 'param' is not writable or has an invalid setter method.

like image 851
Saul Avatar asked May 05 '15 19:05

Saul


1 Answers

In my own projects, I get the implementor to supply me with the dependency supplied by spring's DI container.

Reworking the code above, this would look like this:

public interface MyProcessor {

  // get the implementor to get the hash map
  WeakHashMap<Function1D, Integer> getParamMap();

  default double doSomthingWithParam(double x) {  
    return doSomething() * getParam();
  } 

  // uses the implementor's getParamMap() to get params
  default int getParam() {
    return getParamMap().get(this);
  } 

  double doSomething();
}

public class MyProcessorImp extends SomeClass implements MyProcessor {

  final WeakHashMap<Function1D, Integer> paramMap = new WeakHashMap<>();

  void setParam(int param) {
    paramMap.put(this, param);
  }

  @Override WeakHashMap<Function1D, Integer> getParamMap() {
    return paramMap;
  }

  @Override double doSomething() { 
    // elided 
  }
} 
like image 127
Philippe Avatar answered Sep 17 '22 13:09

Philippe