Vitaliy
Vitaliy

Reputation: 8206

Is it possible to use Spring without a configuration file?

In my unit tests I want to configure Spring in code (API, Annotations) so they will not depend on bean configuration files.

Can this be done?

For example:

Class Dependency {}

Class A
{
    @AutoWired
    Dependency d;
}

When testing A, I want to be able to create an instance of it with the Dependency member resolved, without having to use configuration files.

Thank you!

Upvotes: 0

Views: 56

Answers (3)

user1613360
user1613360

Reputation: 1314

You can use the AnnotationConfigApplicationContext to create application context programatically without bean configuration files.

Upvotes: 0

Filipe Fedalto
Filipe Fedalto

Reputation: 2540

In short, yes, you can start a spring application context with any of the implementations of org.springframework.context.support.AbstractApplicationContext. Namely, if you don't want to load the definitions from an XML file, you can use the org.springframework.context.support.StaticApplicationContext or org.springframework.context.support.GenericApplicationContext to start the context.

With the context instantiated, you can start creating beans with the BeanFactory, either the oen default to the selected context or a custom one, that suits your needs.

In practice, it's lot more work than that. It's easier if you just use plain XML configuration, but it can be done.

Upvotes: 1

Ray Toal
Ray Toal

Reputation: 88428

You can use the Java configuration instead of the XML configuration.

Upvotes: 0

Related Questions