Java Reference
In-Depth Information
This is equivalent to an XML application context with the following definition:
<bean id="josh" class="com.apress.springenterpriserecipes.
➥
spring3.javaconfig.Person" p:name="Josh" />
You can access the bean from your Spring application context just as you would normally:
ApplicationContext context = … ;
Person person = context.getBean("josh", Person.class);
If you want to specify the
id
of the bean, you can do so by using the
@Bean
definitions
id
attribute:
@Bean(name="theArtistFormerlyKnownAsJosh")
public Person josh() {
// …
}
You can access this bean as follows:
ApplicationContext context = … ;
Person person = context.getBean("theArtistFormerlyKnownAsJosh", Person.class);
Now, I know what you're thinking: how is
that
an improvement? It's five times more lines of code!
You mustn't dismiss the inherent readability of the Java example. Similarly, if the example compiles, you
can be reasonably sure that your configuration was correct. The XML example doesn't afford you any of
those benefits.
If you want to specify life cycle methods, you have choices. Life cycle methods in Spring were
formerly implemented as callbacks against known interfaces, like
InitializingBean
and
DisposableBean
,
which gets a callback after dependencies have been injected (
public void afterPropertiesSet() throws
Exception
), and before the bean is destroyed and removed from the context (
public void destroy()
throws Exception
), respectively. You may also configure the initialization and destruction methods
manually in the XML configuration, using the
init-method
and
destroy-method
attributes of the bean
xml element. Since Spring 2.5, you can also use JSR-250 annotations to designate methods as an
initialization (
@PostConstruct
) and destruction method (
@PreDestroy
). In JavaConfig, you have yet one
more option!
You can specify the life cycle methods using the
@Bean
annotation or you can simply call the method
yourself! The first option, using the
initMethod
and
destroyMethod
attributes, is straightforward:
@Bean( initMethod = "startLife", destroyMethod = "die")
public Person companyLawyer() {
Person companyLawyer = new Person();
companyLawyer.setName("Alan Crane");
return companyLawyer;
}
However, you can readily handle initialization on your own, too:
@Bean
public Person companyLawyer() {
Person companyLawyer = new Person();
companyLawyer.startLife() ;
companyLawyer.setName("Alan Crane");
return companyLawyer;
}
Search WWH ::
Custom Search