spring annotation @ Service annotation usage analysis

  • 2021-11-01 03:23:20
  • OfStack

Use of @ Service annotations

To explain @Service The use of annotations, we have to say 1, we often in spring Configuration file applicationContext.xml See the configuration in the following figure:


<!--  Adopt scanning  +  Annotations for development   It can improve the development efficiency, and the later maintenance becomes difficult and the readability becomes poor  -->
<context:component-scan base-package="com.study.persistent" />

In applicationContext.xml After this 1 line is added to the configuration file, packages under the specified path will be automatically scanned if 1 class takes @Service Annotation, will be automatically registered to the Spring Container, no longer needed in applicationContext.xml Defined in the configuration file bean Yes, similar ones include @Component , @Repository , spring0 .

Such as this class:


@Service("courseDAO")
@Scope("prototype")
public class CourseDAOImpl extends HibernateDaoSupport implements CourseDAO{
......
}

Its function is equivalent to the applicationContext.xml The following information is configured in the configuration file:


<bean id="courseDAO"
      class="com.study.persistent.CourseDAOImpl" scope="prototype">
      ......    
</bean>

@Service("serviceName") Annotations are equivalent to applicationContext.xml Configured in the configuration file <bean id="serviceName"> Give the current class an alias, which is convenient to inject into other classes that need to be used.

@Service Annotations can also be left unspecified serviceName If you do not specify an equivalent to <bean id="com.study.service.serviceName"> , com.study.service.ServiceName Is the fully qualified name of this class. If not, the default alias is the current class name, but the first letter is lowercase.

Brief introduction and application example of @ service annotation

The annotation that appears after spring2.5 follows the spring Configured in the configuration file bean The same function is to make spring Automatic scan management component, @Service , spring0 , @Repository , @Component These four are actually one kind of function, there is no difference, just in MVC The layers represented on the pattern are different, service 1 is marked in service Layered bean Go, applicationContext.xml0 Mark on the control layer, @Repository Marked in applicationContext.xml2 Layer, component General.


Related articles: