开发者

Why the following does not work for autowired

开发者 https://www.devze.com 2023-03-03 06:00 出处:网络
I have a class like class A { @Autowired B b; } A a = new A() I found b is not autowired I already did &l开发者_JAVA百科t;context:component-scan base-package=\"*\">, anything else missing?You

I have a class like

class A {
      @Autowired
      B b;
}

A a = new A()

I found b is not autowired

I already did &l开发者_JAVA百科t;context:component-scan base-package="*">, anything else missing?


You have to get the bean from a bean factory, instead of creating an instance directly.

For example, here's how to do it with annotations. First, you need to add a bit more to your declaration of your class:

// Annotate to declare this as a bean, not just a POJO
@Component
class A {
    @Autowired
    B b;
}

Next, you do this once per application:

AnnotationConfigApplicationContext factory =
        new AnnotationConfigApplicationContext();
factory.register(A.class);
factory.register(B.class);
// Plus any other classes to register, or use scan(packages...) method
factory.refresh();

Finally, you can now get instances of the bean:

// Instead of: new A()
A a = factory.getBean(A.class);


Spring will only autowire the A object if Spring instantiates it as a bean. if you instantiate your own, Spring knows nothing about it, so nothing gets autowired.

0

精彩评论

暂无评论...
验证码 换一张
取 消