自动装配不适用于原型bean中的bean

时间:2019-03-30 10:13:46

标签: java spring-boot

我正在构建REST服务API,我想从REST Controller中调用另一个实现类。 我从MyController创建ServiceImpl的bean,并且ServiceImpl使用Customer对象。 (仅用于测试客户的预期是单例)。 我正在尝试访问原型bean内的bean,但Null Pointer失败。


@RestController
public class MyController {

    static int i = 0;
    public MyController() {
    System.out.println("Inside Controller");
    }

    @RequestMapping("/")
    public int post(ServiceImpl impl) {
    return impl.name(i++);
    }

}

public class Customer {

    String name;

    public Customer() {
    System.out.println("inside customer cons");
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

}

@Configuration 
public class ServiceConfigurations {

    @Bean
    public Customer Customer() {
    return new Customer();
    }   

}

@Component
@Scope(value = "prototype")
public class ServiceImpl {

    int i = 0;

    @Autowired
    Customer c;

    public int name(int name) {
    c.getName();  // Fails with null pointer
    return i++;
    }

}

对于@Autowire for Customer为什么不设置参考,有何帮助?

1 个答案:

答案 0 :(得分:0)

这里的问题是您的 false 期望
这些行

@RequestMapping("/")
public int post(ServiceImpl impl)

实际上并没有@Autowire一个新的ServiceImpl Bean,他们只是创建了一个ServiceImpl的新实例。完全不进行注射。

有关Bean范围及其使用方法的概述,请参见Spring Bean scopes

相关问题