Friday, July 13, 2018

Spring in Action 4th Edition

Spring in Action 4th Edition

1. The act of creating associations between application components is commonly
referred to as wiring. In Spring, there are many ways to wire components together, but
a common approach has always been via XML.
2. In a Spring application, an application context loads bean definitions and wires them
together. The Spring application context is fully responsible for the creation of and
wiring of the objects that make up the application.
For XML based, ClassPathXmlApplicationContext
For Java-based configurations, Spring offers AnnotationConfigApplicationContext.
3.
Spring attacks automatic wiring from two angles:
a. Component scanning—Spring automatically discovers beans to be created in the
application context.
b. Autowiring—Spring automatically satisfies bean dependencies.
4.
@Component. This simple annotation identifies this class as a component class and
serves as a clue to Spring that a bean should be created for the class.
With no further configuration, @ComponentScan will default to scanning the same
package as the configuration class. Therefore, because CDPlayerConfig is in the
soundsystem package, Spring will scan that package and any subpackages underneath
it, looking for classes that are annotated with @Component. It should find the Compact-
Disc class and automatically create a bean for it in Spring.

@Configuration
@ComponentScan(basePackageClasses={CDPlayer.class, DVDPlayer.class})
public class CDPlayerConfig {}

With a
marker interface, you can still have a refactor-friendly reference to an interface, but
without references to any actual application code

Put succinctly, autowiring is a means of letting Spring automatically satisfy a bean’s
dependencies by finding other beans in the application context that are a match to
the bean’s needs. To indicate that autowiring should be performed, you can use
Spring’s @Autowired annotation.

The @Autowired annotation’s use isn’t limited to constructors. It can also be used on a
property’s setter method.

Actually, there’s nothing special about setter methods. @Autowired can also be
applied on any method on the class.

When required is false, Spring will attempt to perform autowiring; but if there are no
matching beans, it will leave the bean unwired. You should be careful setting required
to false, however. Leaving the property unwired could lead to NullPointer-
Exceptions if you don’t check for null in your code.
The key to creating a JavaConfig class is to annotate it with @Configuration.

5.
By default, all beans in Spring are singletons

No comments:

Post a Comment