You can achieve the desired behavior by pointing the bean to proxyMode ScopedProxyMode.TARGET_CLASS (CGLIB) or ScopedProxyMode.INTERFACES (JDK).
for instance
public class StackOverflow { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Conf.class); Bar bar = ctx.getBean(Bar.class); System.out.println(bar); System.out.println(bar.foo.toString()); } } @Configuration class Conf { @Bean @Lazy @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) public Foo foo() { System.out.println("heyy"); return new Foo(); } @Bean public Bar bar() { return new Bar(); } } class Bar { @Autowired public Foo foo; } class Foo { }
will print
com.example.Bar@3a52dba3 heyy com.example.Foo@7bedc48a
demonstrating that the Foo bean was initialized using the @Bean factory method only after calling the method in the Foo instance introduced by the Spring context in the Bar bean.
The @Scope annotation @Scope also be used in a class declaration.
source share