@Configurable无法处理子类

时间:2017-08-16 08:32:09

标签: spring spring-aop

采用以下一般抽象类:

@Configurable
    public abstract class TestEntityRoot {
    public abstract String print();
}

一个子类:

@Configurable
public class TestEntity extends TestEntityRoot{

    private TestEntityService testEntityService;

    @Autowired
    public void setTestEntityService(TestEntityService testEntityService) {
        this.testEntityService = testEntityService;
    }

    @Override
    public String print() {
        return testEntityService.print();
    }
}

当呼叫控制器:

@RestController
public class TestEntityController {

    @GetMapping(name = "/test")
    public String print() {
        TestEntity entity = new TestEntity();
        return entity.print();
    }
}
一切都好。但如果这样打电话:

@RestController
public class TestEntityController {

    @GetMapping(name = "/test")
    public String print() {
        TestEntityRoot entity = new TestEntity();
        return entity.print();
    }
}

我得到空指针。第二个例子可能有效吗?

1 个答案:

答案 0 :(得分:1)

在第二种情况下,您手动创建类而不是使用spring的bean。自动装配bean。参见

@RestController
public class TestEntityController {
    @Autowired
    private TestEntity entity
    @GetMapping(name = "/test")
    public String print() {
        return entity.print();
    }
}