79526367

Date: 2025-03-21 18:50:39
Score: 0.5
Natty:
Report link

I sympathise with your desire to stay DRY but I don't think it can be done.

I think it is safer to achieve your aim as follows:

@Component
public class WrappedBean {

    @Autowired
    public SomeBean starterBean;

    @Bean
    WrappedBean wrappedBean() {
        this.starterBean.doSomethingCustom();
        return this;
    }
}

Then access it as follows:

    @Autowired
    WrappedBean someOtherBean;
    
    SomeBean someBean;
    

    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() {
        someBean = someOtherBean.starterBean;
    }

These are attempts to subvert the Spring mechanisms/sequence.

Pulling the starter created bean directly from applicationContext:

@Configuration
@Lazy
public class MyConfiguration {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    SomeBean someOtherBean() {
        SomeBean starterBean = (SomeBean) applicationContext.getBean("someBean");
        starterBean.doSomethingCustom();
        return starterBean;
    }
}

Resulted in error:

Field someOtherBean in com.example.abstractunmarshallexception.AbstractunmarshallexceptionApplication required a bean named 'someBean' that could not be found.

Messing about with @Qualifier

@Configuration
@Lazy
public class MyConfiguration {

      @Autowired
      private SomeBean starterBean;

      @Autowired
      private ApplicationContext applicationContext;

    @Bean
    SomeBean someOtherBean() {
        starterBean.doSomethingCustom();
        return starterBean;
    }
}

and usage:

    @Autowired
    SomeBean someOtherBean;

Results results in error as follows:


Error creating bean with name 'someOtherBean': Requested bean is currently in creation: Is there an unresolvable circular reference or an asynchronous initialization dependency?
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • User mentioned (1): @Qualifierand
  • High reputation (-1):
Posted by: John Williams