Java Reference
In-Depth Information
Referencing other beans is as simple and very similar:
@Configuration
public class PetConfiguration {
@Bean
public Cat cat(){
return new Cat();
}
@Bean
public Person master(){
Person person = new Person() ;
person.setPet( cat() );
return person;
}
// ...
}
It simply doesn't get any easier than that: if you need a reference to another bean, simply obtain the
reference to the other bean just as you would in any other Java application. Spring will ensure that the
bean is instantiated only once and that scope rules are applied if relevant.
The full gamut of configuration options for beans defined in XML is available to beans defined via
JavaConfig.
The @Lazy , @Primary , and @DependsOn annotations work exactly like their XML counterparts. @Lazy
defers construction of the bean until it's required to satisfy a dependency or it's explicitly accessed from
the application context. @DependsOn specifies that the creation of a bean must come after the creation of
some other bean, whose existence might be crucial to the correct creation of the bean. @Primary specifies
that the bean on whose definition the annotation is placed is the one that should be returned when there
are multiple beans of the same interface. Naturally, if you access beans by name from the container, this
makes less sense.
The annotations sit above the bean configuration method to which it applies, like the other
annotations. Here's an example:
@Bean @Lazy
public NetworkFileProcessor fileProcessor(){ … }
Often, you'll want to partition your bean configuration into multiple configuration classes, which
leaves things more maintainable and modular. Pursuant to that, Spring lets you import other beans.
In XML you do this using the import element ( <import resource="someOtherElement.xml" />). In
JavaConfig, similar functionality is available through the @Import annotation, which you place at the
class level.
@Configuration
@Import(BusinessConfiguration.class)
public class FamilyConfiguration {
// ...
}
This has the effect of bringing into scope the beans defined in the BusinessConfiguration . From
there, you can get access to the beans simply by using @Autowired or @Value if you want. If you inject the
ApplicationContext using @Autowired , you can use it to obtain access to a bean. Here, the container
imports the beans defined from the AttorneyConfiguration configuration class and then lets you inject
them by name using the @Value annotation. Had there been only one instance of that type, you could
have used @Autowired .
Search WWH ::




Custom Search