spring注解@Service注解的使用

 要说明@Service注解的使用,就得说一下我们经常在spring配置文件applicationContext.xml中看到如下图中的配置:

<!-- 采用扫描 + 注解的方式进行开发 可以提高开发效率,后期维护变的困难了,可读性变差了 -->
<context:component-scan base-package="com.study.persistent" />

 在applicationContext.xml配置文件中加上这一行以后,将自动扫描指定路径下的包,如果一个类带了@Service注解,将自动注册到Spring容器,不需要再在applicationContext.xml配置文件中定义bean了,类似的还包括@Component、@Repository、@Controller。

如这个类:

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

 其作用就相当于在applicationContext.xml配置文件里配置如下信息:

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

 @Service("serviceName")注解相当于applicationContext.xml配置文件中配置的<bean id="serviceName">,表示给当前类命名一个别名,方便注入到其他需要用到的类中。@Service注解也可以不指定serviceName,如果不指定相当于<bean id="com.study.service.serviceName">,com.study.service.ServiceName就是这个类的全限定名,不加的话,默认别名就是当前类名,但是首字母小写。

猜你喜欢

转载自jiangyupeng.iteye.com/blog/2408908