Spring comes at automating bean assembly from two perspectives

  1. Component scanning: Spring automatically discovers beans created by the application context
  2. Autowiring: Sring automatically satisfies dependencies between beans

Component scanning and auto-assembly minimize the configuration displayed

Classes annotated with @Componet will be used as Component classes, and Spring will create beans for that class. Component scanning is not turned on by default. We need to show spring’s configuration so that it looks for classes annotated with @Component and creates beans for them

Enable component scanning using the @ComponentScan annotation

By default, @ComponentScan scans packages (including subpackages) that are the same as the configuration class.

Name the bean that scans the component

Spring context beans will have an ID. If no ID is explicitly specified, the class name is used as the ID by default (the first letter will be lowercase).

@Component("lonelyHeartsClub") 
// This assigns an ID to the bean
Copy the code

We can also mark Component classes with the @named annotation. The difference between @named and @Component is subtle and most scenarios are interchangeable

@named is an annotation provided by the Java dependency injection specification that Spring supports

If @ComponentScan doesn’t have any attributes, it follows the default rules to scan components based on the base package in which the configured class is located

But what if we want to scan different packages.

All we need to do is specify the package in the value property of the @ComponentScan annotation

If we want to set multiple packages, we set the basePackages property to the array of packages to scan.

In the above case, the base package is represented by character creation. This method is not type safe, and if you refactor the code, the specified base package may be wrong

@ComponentScan also has a basePackageClasses property that sets classes and sping will base them on the same package

Automatically.

Autowiring is one way to make Spring automatically satisfy bean dependencies. We use the @AutoWired annotation (injected by type) and @AutoWired can be used on constructors,setter methods, and properties