Reputation: 431
I am using Spring @Configuration
annotation to configure my application.
Currently, I have a single @Configuration
class where all my beans are declared. As the number of beans is growing (more than 30), I want to split it in many classes.
Some beans are using common classes (mainly utility classes) :
Foo.class is an utility class Bar.class and Baz.class both use Foo.class
I want to have all Foo, Bar and Baz
in three distinct @Configuration
classes (respectively Conf1, Conf2 and Conf3
)
The problem is that I don't have access to an instance of Conf1
from Conf2 and Conf3
:
Conf1.class
@Configuration
public class Conf1 {
@Bean
public Foo foo() {
return new Foo();
}
}
Conf2.class
@Configuration
public class Conf2 {
@Bean
public Bar bar() {
Bar bar = new Bar();
bar.setFoo(conf1.foo()); // Not possible !
return bar;
}
}
Conf3.class
@Configuration
public class Conf3 {
@Bean
public Baz baz() {
Baz baz = new Baz();
baz.setFoo(conf1.foo()); // Not possible !
return baz;
}
}
Any idea on how can I solve this issue ?
Upvotes: 22
Views: 41978
Reputation: 7861
Spring framework chapter-5 explained it very nicely.
@ExternalBean : One configuration class may need to reference a bean defined in another configuration class (or in XML, for that matter). The @ExternalBean annotation provides just such a mechanism. When JavaConfig encounters a method annotated as @ExternalBean, it replaces that method definition with a lookup to the enclosing bean factory for a bean with the same name as the method name
@Import : @Import represents JavaConfig's equivalent of XML configuration's element. One configuration class can import any number of other configuration classes, and their bean definitions will be processed as if locally defined
ConfigurationSupport : As a convenience, @Configuration classses can extend ConfigurationSupport, primarily in order to facilitate easy lookup of beans from the enclosing BeanFactory / ApplicationContext.
Upvotes: 4
Reputation: 302
@Configuration
@Import({ DataSourceConfig.class, TransactionConfig.class })
public class AppConfig extends ConfigurationSupport {
// bean definitions here can reference bean definitions in DataSourceConfig or TransactionConfig
}
Upvotes: 25
Reputation: 242776
You should be able to autowire them:
@Configuration
public class Conf2 {
@Autowired
Conf1 conf1;
...
}
Alternatively, you can autowire beans rather than configurations:
@Configuration
public class Conf2 {
@Autowired
Foo foo;
...
}
Upvotes: 21