不光是@Service注解,还有其他的三个: @Controller, @Repository, @Component.
别人的:
说明@Service注解的使用,就得说一下我们经常在spring配置文件applicationContext.xml中看到如下图中的配置:
1 | <!-- 采用扫描 + 注解的方式进行开发 可以提高开发效率,后期维护变的困难了,可读性变差了 --> |
applicationContext.xml(以前的做法)配置文件中加上component-scan之后,就自动扫描路径下的包,注入到spring容器;- 而如果一个类带了
@Service注解, 就自动注入到spring容器,不需要applicationContext.xml配置文件中定义bean了。 - 类似的包括
@Controller,@Repository,@Component.
What do we learn from above?
自己的感悟:
也就是说,@Service(和另外三个), 是标识符,注解一个类(不能是接口), 那么这个类对应的bean就自动注入到spring容器,而不用手动在applicationContext.xml配置文件中手动component, component-scan.
@Service中的参数有什么卵用?
e.g. 这个类:1
2
3
4
5@Service("courseDAO")
@Scope("prototype")
public class CourseDAOImpl extends HibernateDaoSupport implements CourseDAO{
......
}
就相当于在applicationContext.xml配置文件中配置:1
2
3
4<bean id="courseDAO"
class="com.study.persistent.CourseDAOImpl" scope="prototype">
......
</bean>
i.e.
@Service("courseDAO")->bean: id="courseDAO" ...@Scope("prototype")->scope="prototype"
也就是说, @Service("serviceName")注解相当于applicationContext.xml配置文件中配置的<bean id="serviceName">, 表示给当前类命名一个别名,方便注入到其他需要用到的类中.
@Service注解也可以不指定serviceName,如果不指定相当于<bean id="com.study.service.serviceName">,com.study.service.ServiceName就是这个类的全限定名,