Remember a mistake about the use of SSM framework

Today, I encountered a very fucking problem. Finally, I found that I forgot to add @ Autowired to the corresponding service.

No wonder there is no problem with unit testing, because the implementation classes of the service used in unit testing are automatically assembled through Dao. That is, in the corresponding spring mybatis Bean is configured with XML.

For the controller, calling the corresponding business service requires manually adding @ Autowired annotation to realize assembly.

So what is automatic assembly?

To put it simply, if spring manages objects, how does spring manage objects? Manage through configuration files.

For example, how many common ways are there for automatic assembly?

The first is the @ Autowired annotation, which will automatically inject the service name into XML, such as:

However, although this method is automated, it also has its limitations, that is, when scanning the service layer, the same testservice cannot exist, otherwise an error will be reported.

The second is the @ resource annotation, which can be automatically assembled or assigned a name.

The reason why the name is specified is to prevent repeated service injection from causing an error.

Here is the difference between @ Autowired and @ resource:

(1) Both @ Autowired and @ resource can be used to assemble beans Can be written on fields or setter methods;

(2) @ Autowired assembles by type by default (this annotation belongs to spring). By default, dependent objects must exist. If null value is allowed, its required property can be set to false, such as @ Autowired (required = false). If we want to use name assembly, we can use it in combination with @ qualifier annotation, as follows:

(3)@Resource (this annotation belongs to J2EE). It is assembled by name by default, and the name can be specified through the name attribute. If the name attribute is not specified, when the annotation is written on the field, it will take the field name by default to find the installation name. If the annotation is written on the setter method, it will take the property name by default to assemble. When the bean matching the name cannot be found, it will be assembled by type. However, it should be noted that once the name attribute is specified, it will only be assembled by name.

Generally, in order to reduce assembly conflicts, @ resource is recommended.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>