Question

I'm reading Spring documentation and I stumbled across a piece of text that made me ponder a bit.

You use getBean() to retrieve instances of your beans. The ApplicationContext interface has a few other methods for retrieving beans, but ideally your application code should never use them. Indeed, your application code should have no calls to the getBean() method at all, and thus no dependency on Spring APIs at all.

Well, I configured beans in my xml file. But I still need retrieve them when in need. How can I do that without getBean() method? The more detailed explanation, the better.

Was it helpful?

Solution

You need some way to retrieve Spring beans when you want to access them from classes that were not created by Spring, e.g. the main class in a command line program, and you use the getBean methods for that.

But Spring beans themselves do seldom need this feature, because it is Spring's responsibility to provide the other beans that are required, via constructor arguments or setter methods (this is the basic idea behind dependency injection).

OTHER TIPS

The basic idea is "don't call us, we'll call you", meaning that your code doesn't ask Spring IOC (Inversion of Control)-container for the beans, but rather the container injects the beans into your code. The injections are configured either using xml-configuration file(s) or via annotations. For more details, see for example this and this. Also I'd recommend reading the whole chapter 3 from the reference manual (as you probably are doing).

The ApplicationContext-interface still makes it possible to ask for beans programmatically, which might be needed in some special cases, for example when integrating with some other framework or such.

Some time ago I wrote some generic parser that could handle different input file formats.

class XmlFormat extends Format {
    // format stuff
    // ...
}

class Parser {
    Format format;

    public Parser(Format format) {
        this.format = format;
    }

    // parsing goes here
    // ...
}

Next I told Spring which format description was to use. (Disclaimer: Your Spring config may have a very different style.)

<bean id="forma1" class="com.mycompany.XmlFormat" />

<bean id="parser" class="com.mycompany.Parser">
    <constructor-arg ref="format1">
</bean>

So now when I wanted Spring to give me a Parser, it injected the XmlFormat into the constructor for me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top