“This article has participated in the good Article call order campaign, click to view:Back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

I’m a little grey ape, a programmer who can write bugs!

In the previous article, we explained the basic introduction of Spring development, including the instantiation of bean objects in IOC and how to obtain related objects from IOC. But in real development, ** if there are many analogies, then it is too troublesome to add and instantiate one by one? Think bald… ** today will teach you how to efficiently improve Java development efficiency!!

How could any good programmer not have thought of this? So there are annotations for more concise development…

Use annotations to identify components

In order not to declare class objects one by one in IOC, Spring first defines component-based annotations according to the different functions of each class, which can be roughly divided into the following four types:

① Common components: @component

Identifying a component managed by the Spring IOC container can also be interpreted as an annotation used by components other than the database layer, business logic layer, and control layer components.

(2) Persistence layer component: @respository

Identifying a persistence layer component managed by the Spring IOC container is typically used to annotates the database layer

③ Service logic layer component: @service

Identifies a business logic layer component managed by the Spring IOC container,

④ Controller components at the presentation layer: @controller

Identifies a presentation layer controller component that is managed by the Spring IOC container.

If you do not set value, the default ID is the full name of the class (lowercase first letter).

In the following example, we add a @respository annotation for a Dao layer component

/** * @repository public class BookDao {public void saveBook() {system.out.println (" The book in the BookDao has been saved...") ); }}Copy the code

With these four annotations we can first classify all the components one by one. In the final analysis, the reason why we use annotations for classification is to quickly and conveniently know which class does what type of function, and at the same time, it is convenient to add components into the IOC container through these four annotations.

So you can also think of these four annotations as an “identity card” that Spring distributes to different functional components, and that component can be added to the IOC container only if it has these four identity cards.

** One thing to note here: **** In fact, Spring does not have the ability to identify whether a component is of the type marked by it, ** using the @respository annotation on a presentation layer controller component does not cause any errors. So the @respository, @Service, and @Controller annotations are just for the developer to know what role the current component plays. Easy to add components to a container.

2. Component scanning

1. General scanning

Now all the components are classified in detail, but does this mean that all the components have been added to the IOC container? If that’s true, then we’re truly in the low-code era…

** So how do we add an annotated component to the IOC container? Spring provides a package scanning function in IOC. Spring automatically scans all the components marked with these four annotations throughout the project and adds them to the IOC container.

To perform a package scan, look like this:

** Package scanning depends on the Context namespace, so you need to add this namespace to IOC. There are two ways to add this namespace, ** One is to add the following code to the IOC header file:

xmlns:context="http://www.springframework.org/schema/context"
Copy the code

But it’s not recommended because it’s hard to remember,

Another way to do this is to go to the bottom of the page and click on Namespaces and go to Context,

The code for scanning packages in the container is:

<context:component-scan base-package="com.spring"></context:component-scan>
Copy the code

The base-package attribute specifies a base class package to be scanned. The Spring container will scan all classes in the base class package and its subpackages. When multiple packages need to be scanned, use commas to separate them. ** The code above scans all classes under the com.spring package.

2. Include and exclude specific components

But the scope of scanning is sometimes too large, so can you narrow down the scope of packet scanning? Of course you can.

If you only want to scan for specific classes and not all classes in the base package, you can use the resource-pattern attribute to filter for specific classes.

<context:component-scan base-package="com.atguigu.component" resource-pattern="autowire/*.class"/>
Copy the code

(1) Scan contains specific components

** If we only want to scan components that contain certain characteristics, ** then we can do the following:

context:include-filterThe child node represents the target class to include

But it’s important to note: Since context: Component-scan defaults to adding all classes, it is useless to add classes on top of this. You need to add the use-default-filters attribute to context: Component-scan. Use-default-filters =”true” if all classes are added by default, false if all classes are not added by default,

The following code indicates that only the components containing the features indicated in the includefilter are scanned. Type indicates the type of the scan expression. Expression is followed by an expression.

<context:component-scan base-package="com.spring" use-default-filters="false"> <context:include-filter type="annotation"  expression="org.springframework.stereotype.Repository"/> </context:component-scan>Copy the code

(2) Scan to exclude specific components

Where there are scans that contain certain components, there are scans that exclude certain components,

context:exclude-filterThe child node represents the target class to exclude.

The following code indicates scanning for components other than the following characteristics.

<context:component-scan base-package="com.spring">
    <context:exclude-filter type="assignable" expression="com.spring.service.BookService"/>  
</context:component-scan> 
Copy the code

In addition, component-scan can have several include-filter and exclude-filter child nodes to indicate that components with specific characteristics can be included or excluded.

The following table describes the types and functions of filter expressions in the above mentioned type:

category

The sample

instructions

annotation

com.atguigu.XxxAnnotation

Filter all classes that annotate xxxAnnotations. This rule filters based on whether the target component has annotations of the specified type.

assignable

com.atguigu.BaseXxx

Filters all subclasses of BaseXxx. This rule filters based on how the target component is a subclass of the specified type.

aspectj

com.atguigu.*Service+

All class names end in Service, or subclasses of such classes. This rule filters according to AspectJ expressions.

regex

com\.atguigu\.anno\.*

All classes under the com.atguigu.anno package. This rule filters based on the class name matched by the regular expression.

custom

com.atguigu.XxxTypeFilter

Use the XxxTypeFilter class to define filter rules by encoding. The class must implement the org. Springframework. Core. The filter. The TypeFilter interface

While the top two are most commonly used, the following three are rarely used:

Type =” aspectJ “AspectJ expression

Type =”custom” define a TypeFile and write your own class to define which one to use

Type =”regex” uses regular expressions

**** Be aware of bugs: some people write annotations and scans perfectly, but they don’t work, perhaps because they lack a specific JAR package and need to import an additional AOP package

Spring aop — 4.0.0. RELEASE. The jar

At this point, adding the component to the container is done,

After we successfully add the component, we can see a small S icon in the upper right corner of the component icon, which indicates that the component has been successfully added to the container.

3. Three steps to implement annotations

To summarize the three steps to implementing annotations:

  1. Adding context dependencies

    context:component-scan
  2. Add the appropriate annotations to the class
    1. Import the aop package

      Spring aop — 4.0.0. RELEASE. The jar

3. Automatic assembly of components

But is that the end? Is that how easy it is? What about the scope and lifecycle of beans? Of course not! More importantly, the component has not been obtained yet!!

So next to talk about the use of annotations development of high-end operations, let you know how fragrant using annotations!!

For example, the Controller component often needs an instance of the Service component, and the Service component often needs an instance of the Repository component.

Wouldn’t it be too much trouble if we instantiated each of these components one by one? Alas, how could any clever programmer not have thought of this! So auto-assembly of components came into being,

In Spring we can automatically assemble components through annotations, so how do we assemble components?

The truth is, when you specify the package to scan in IOC,context:component-scanRear element will automatically register a bean processors: AutowiredAnnotationBeanPostProcessor instance. The post-processor can auto-assemble properties marked with @Autowired, @Resource, or @Inject annotations.

The @autowired, @Resource, or @Inject annotations above are the most common annotations we use when auto-assembling components.

Let me introduce the specific use of these three annotations.

1, @autowired annotation

The @autoWired annotation enables auto-assembly by type. The @AutoWired annotation can be applied to constructors, normal fields (even if they are non-public), or any method that has arguments

By default, all properties annotated with @Autowired need to be set. Spring throws an exception when it cannot find a matching bean assembly property.

(1) @Autowired Assembly principle

Next, LET me talk about the assembly principle of @Autowired annotation in detail:

1. When using autoassemble, we first look for the corresponding component in the container by type, which is similar to

GetBean (” bookService class “),

Throw an exception if no one is found, assign a value if one is found

3. If more than one is found, there is a certain basis for assembly, and it is not random to find one for assembly.

Firstly, the search continues according to the attribute name as the ID. If the component with the corresponding attribute name is found, the assembly will be carried out. If it is not found, an error will be reported

Qualifier specifies the assembly ID

Select * from @qualifier (“bookService”) where ID = ID and ID = ID = ID; select * from @qualifier (“bookService”) where ID = ID and ID = ID;

@autowired @qualifier ("bookdao") private bookdao Bookdao;Copy the code

(3) Required — Assembly error resolved

Wouldn’t it crash if we reported an error every time we couldn’t find it? What should you do in such a situation? There is another solution to this problem: use the required argument,

@autowired (required=false) Required =false means to assemble null if it cannot be found

Anyway, the basis of assembly is to look for the appropriate assembly object according to various rules until it succeeds, and then return null if it fails.

(4) Automatic assembly of special attributes

Above are the basic principles and steps of using @Autowired annotations, and we know that annotation development for Spring is very powerful. Next, let’s look at the assembly of a few special properties.

The @autowired annotation can be applied to a property of an array type, at which point Spring will auto-assemble all matching beans.

The @autowired annotation can also be applied to a collection property, where Spring reads the type information for the collection and then automatically assembles all beans that are compatible with it.

When the @autowired annotation is used on java.util.Map, if the Map’s key value is String, Spring will auto-assemble the bean compatible with the value type as the value and the bean’s ID value as the key.

In this way, @autowired annotated automatic assembly is not very powerful, later mom no longer need to worry about my new object!!

2. @resource annotation

The @resource annotation requires an attribute of the bean name. If this attribute is empty, the variable or method name at the annotation is automatically taken as the name of the bean.

3, @inject annotation

The @inject annotation, like the @Autowired annotation, also injects matching beans by type, but without the reqired attribute.

So those are the three annotations that you use when you do autowiring, and to summarize here,

@autowried comes with Spring and is a little more powerful, with the ability to implement required=false

@Resource also comes with Java and is more extensible, so if you switch to another container framework, @Resource is still available, and @inject is the same as the @Autowired annotation that injects matched beans by type, but without the reqired attribute. In fact, the most frequently used and powerful annotation in daily development is the @Autowired annotation. So just keep this one in mind, basically.

The main benefit of using annotations is to save trouble when using new objects. Spring can automatically assign a value to this property by using an @Autowired annotation. Generally, annotations that add components to IOC are used in conjunction with @Autowired.

Four, note the use of small details

In fact, there are a few small details to pay attention to when using annotations for development, which I will summarize here.

1. Consolidate multiple profiles

When we develop projects that are too large, writing a configuration in one configuration file is sometimes not enough, so Spring allows for configuration file integration by importing multiple configuration files into a single file. This way, when you start the Spring container, you only need to specify the merged configuration file. The resource attribute of the import element supports Spring’s standard path resources,

For example, we have two configuration files: springmVc.xml and spring.xml. Now we want to introduce spring.xml into springmVC.xml by writing the following code in springmVC.xml:

<import resource="spring.xml"/>
Copy the code

2. Path writing problem

For common address writing in Spring, sometimes you need to use the classpath, and sometimes you need something else. For different path writing, there are different meanings and uses:

3. Problems obtaining components

The component added to the container using the annotation method is not visible in the IOC container, so how do you get it?

As we said above, spring automatically sets a lower-case component id for each component without specifying an ID (for example, the default id for the Book class is Book). ** The method of retrieving components from the container is the same as before, but if it is a single instance, it is generally recommended to take the class as an argument. Such as:

Book book = (Book)ioc.getBean(Book.class);
Copy the code

Write at the end

This is all about annotations. Annotations are much simpler than native code. Annotations are often used in the SSM framework and later development.

So small partners must study seriously, there are questions can directly private letter me or comment. Like the collection, liver up!!

I’m a little grey ape, and I’ll see you next time!