使用Spring注释将Bean注入带有Property Place的构造函数参数

时间:2016-05-23 19:26:01

标签: java spring spring-boot autowired spring-annotations

我无法将Bean类型从属性文件中注入构造函数参数。 我可以通过直接将值传递给@Qualifier(“beanName”)来注入它,如下所示。

@Component("circle")
public class Circle implements Shape {

}

@RestController  
class MyController {    
    private final Shape shape;

    @Autowired
    public MyClass(@Qualifier("circle")
            Shape shape) {
    this.shape = shape;     
    }
}

但是,以下代码示例不起作用。

返回Null。

@RestController
class MyController {    
    private final Shape shape;

    @Autowired
    public MyClass(@Qualifier("${shape}")
            Shape shape) {
    this.shape = shape;     
    }
}

尝试使用@Resource(name =“$ {shape}”)代替@Qualifier,如此处所述( Spring: Using @Qualifier with Property Placeholder) 但得到编译器错误 “'@ Resource'不适用于参数”

@Resource(“$ {shape}”)给出错误 “无法找到方法'价值'”

这也不起作用:

@RestController
class MyController {    
    @Value("${shape}")
    private final String shapeBean; //Compiler error : "Variable 'shapeBean' might not have been initialised"
    //Not declaring shapeBean as final will give a compiler error at @Qualifier: "Attribute value must be constant"
    private final Shape shape;

    @Autowired
    public MyClass(@Qualifier(shapeBean)
            Shape shape) {
    this.shape = shape;     
    }
}

以下代码也不起作用。在@Qualifier处给出编译器错误:“属性值必须是常量”。

@RestController
class MyController {    
    @Value("${shape}")
    private final String shapeBean;
    private final Shape shape;

    @Autowired
    public MyClass(@Qualifier(shapeBean)
            Shape shape) {
    this.shape = shape;     
    }
}

还尝试了以下内容。两者都试图访问形状时抛出NullPointerException。

@Resource(name="${shape}")
private Shape shape; // In addition, throws a warning saying, "Private field 'shape' is never assigned"

@Autowired  
@Resource(name="${shape}")
private Shape shape;

如果构造函数参数是基元或String,我可以使用@Value(“$ {shape}”)并将值注入变量。但是因为它是一个班级我不知道如何完成它 有人可以告诉我,如果我配置错误或我应该做什么?

1 个答案:

答案 0 :(得分:0)

不会让Circle实现在Shape中定义的所有方法吗? - 只要符合形状合同,你应该没事。现在,如果您有多个形状,例如Triangle,Rectangle和Circle,并且由于某种原因您希望动态加载确切的子类,您可能希望使用ApplicationContext.getBean获取特定的bean("&#34 )。

您可以通过覆盖afterPropertiesSet()来维护对各种可能形状的引用 - 查看InitialingBean并在运行时使用正确的bean。

相关问题