Nuñito Calzada
Nuñito Calzada

Reputation: 2056

spring getting bean using ApplicationContext.getBean()

I want to get a bean of a class A that implements Class B,

public class AndroidDeviceRule implements DeviceRule {}

this is fine

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

But, I would prefer something like

return (DeviceRule) context.getBean(mybeanName, Class<? extends DeviceRule>);

But I can't..

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

Upvotes: 0

Views: 725

Answers (2)

Costi Ciudatu
Costi Ciudatu

Reputation: 38195

What you can do is to define the actual DeviceRule subtype as a generic type at the method level. You can have this in two flavors:

// 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);
}

Upvotes: 0

mirmdasif
mirmdasif

Reputation: 6354

I will recommend Autowiring bean for this

@Autowired
DeviceRule deviceRule;

Much cleaner approach

Upvotes: 1

Related Questions