Replace implementation of bean in spring library project

103 Views Asked by At

I would like to replace the implementation of all created beans of a certain class with proxy with changed logic and additional @Autowired beans there.

I have interface:

public interface Fooable {
    void foo();
}

implementation:

public class FooImpl implements Fooable {
    @Override
    public void foo() {
        throw new UnsupportedOperationException();
    }

    public void foo2() {
        //do smth
    }
}

proxy:

public class FooProxy implements Fooable {
    private final FooImpl fooImpl;
    private final SomethingAutowired somethingAutowired;

    //constructor

    @Override
    public void foo() {
        fooImpl.foo2();
        somethingAutowired.bar();
    }
}

client bean:

@Configuration
public class Config {
    @Bean
    public Fooable fooable1() {
        return new FooImpl();
    }

    @Bean
    public Fooable fooable2() {
        return new FooImpl();
    }
}

I've try to solve this problem in several ways:

  • AOP - problem solved, I just register aspect that I want, but I don't like this way.
  • BPP - I replace bean implementation to proxy class in postProcessAfterInitialization, but I can't autowire custom beans there.
  • BFPP - I changed setBeanClassName, but it doesn't help and as I read this problem shouldn't be solved by BFPP.

I have 2 more ideas, but they are very strange:

  • in BPP save beans in postProcessBeforeInitialization that are needed in the proxy constructor and substitute them in after method
  • in BFPP deregister old bean and register proxy, but idk how to approach this

But I'm sure that there are more clean and beautiful way to solve this.

0

There are 0 best solutions below