简体   繁体   中英

Spring Injection - Interfaces and Classes

I want to be able to call Interfaces in my class, but have spring instantiate them with the right implementation class behind the scenes.

Ie Normally you can do:

IClass clz = new Class();

I want to have the line IClass clz; preferable in the middle of a method (or as one of the attributes if it can't be done), where clz is instantiated to the class I want by Spring.

The reason I'd like to do it this way is because I want to be able to be able to change which implementation I want to use simply by editing the context files.

Even better, would be knowing how to do the above with class contructors that expect parameters. ie new Class(ar1, arg2);

I hope this makes sense. Any help would be much appreciated.

You can make your class implement BeanFactoryAware and then Spring will inject the bean factory in your class. If you then want to get an instance of a class implementing your interface you say something like:

beanFactory.getBean(IClass.class);

If there are multiple beans that implement the same interface you will have to resolve by name. To create a new object each time you ask this, set the bean scope of the bean you're asking for to "prototype".

You can include code such as:

ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
IClass clz = (IClass) context.getBean("beanName");

Not saying this is better per se than Gerco's answer btw, just it's an option, depending what you want to do.

You can also implement the ApplicationContextAware interface: I've found that using ApplicationContext gives me beans with filled-in properties, eg if you have an app.properties file which contains key/value property pairs which you expect to be resolved within the Spring config, beans retrieved via BeanFactory calls may not resolve those.

See this previous SO topic for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM