使用ApplicationContext.getBean()获取bean

时间:2015-05-05 09:24:23

标签: spring spring-mvc

我想获得一个实现B类的A类bean,

public class AndroidDeviceRule implements DeviceRule {}

这很好

return (DeviceRule) context.getBean(myBeanName, DeviceRule.class);

但是,我更喜欢像

这样的东西
return (DeviceRule) context.getBean(mybeanName, Class<? extends DeviceRule>);

但我不能......

- Syntax error on token ",", ( expected after 
     this token
    - Syntax error on token(s), misplaced 
     construct(s)

2 个答案:

答案 0 :(得分:1)

我会为此推荐自动装配 bean

@Autowired
DeviceRule deviceRule;

更清洁的方法

答案 1 :(得分:0)

您可以做的是在方法级别将实际DeviceRule子类型定义为泛型类型。您可以使用两种方式:

// with an explicit type passed in (as in your example)
<T extends DeviceRule> T getSpringBean(String name, Class<T> type) {
    return (T) applicationContext.getBean(name, type);
}


// with no explicit type; will return whatever the caller expects,
// obviously resulting in a ClassCastException if the cast fails.
<T extends DeviceRule> T getSpringBean(String name) {
    return (T) applicationContext.getBean(name);
}