Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autowire bean in StaticApplicationContext

I am trying to autowire a bean in a StaticApplicationContext but although i can insert a bean and retrieve it successfully, I am not able to autowire it in another bean. Below is a simple example to explain what I mean.

In this example, the first assertion is successful, and the second one fails. Note that if I comment out the lines for this approach, and instead uncomment the lines for approach #2 that uses an AnnotationConfigApplicationContext the autowiring works. However I would like to make this work with StaticApplicationContext approach.

@Test
public void testAutowire() {

    //context configuration approach #1
    StaticApplicationContext context = new StaticApplicationContext();
    context.registerSingleton("child", Child.class);

    //context configuration approach #2
    //AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Child.class);

    Parent parent = new Parent();

    context.getAutowireCapableBeanFactory().autowireBean(parent);

    //this is successful
    Assert.notNull(context.getBean(Child.class), "no bean found");
    //this works only with AnnotationConfigApplicationContext and not with StaticApplicationContext
    Assert.notNull(parent.child, "no child autowired");
}

public static class Parent {

    @Autowired
    Child child;

    public Parent() {

    }
}

public static class Child {

    public Child() {
    }
}

Any ideas where the problem lies?

like image 389
Marios Avatar asked Jul 13 '26 22:07

Marios


1 Answers

AnnotationConfigApplicationContext internally registers an AutowiredAnnotationBeanPostProcessor bean to process @Autowired annotations. StaticApplicationContext does not.

You can add it yourself

context.registerSingleton("someName", AutowiredAnnotationBeanPostProcessor.class);

but you then need to refresh the ApplicationContext

context.refresh();
like image 196
Sotirios Delimanolis Avatar answered Jul 16 '26 12:07

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!