Spring mvc注解用到的配置:
<!-- 启用spring mvc 注解 -->
<context:annotation-config />
<context:component-scan base-package="cn.itkt"></context:component-scan>
这样的话,在com包及其所有子包下的所有类如果含有@Component、@Controller、@Service、@Repository等注解的 话都会自动纳入到Spring容器中,但是每个类都一个个加上注解,有时难免觉得繁琐,其实Spring也为我们提供了自动为类加上注解的功能。配置如 下:
<!-- 启用spring mvc 注解 -->
<context:annotation-config />
<!-- 设置使用注解的类所在的包 -->
<context:component-scan base-package="com.lmb.**.rest,com.lmb..server.http,com.lmb.**.mvc">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Service" />
</context:component-scan>
com.lmb..rest,com.lmb.hollyuniproxy.server.http,com.lmb..mvc包下的类都为使用注解的类。
要特别注意其中的context:include-filter标签和context:exclude-filter标签:
context:include-filter
此标签的含义是:在其扫描到的所有包下的类,全部自动加上注解并纳入Spring容器中。
比如下面这个类:
public class InterfaceVisitService implements IInterfaceVisitService {
//……
}
那么该标签等于为InterfaceVisitService 类加上@Component注解,且bean的id为interfaceVisitService。
@Component(“interfaceVisitService”)
public class InterfaceVisitService implements IInterfaceVisitService {
//……
}
context:exclude-filter
此标签的含义是:排除扫描到的所有类,不纳入Spring容器中。
但需要注意的是,采用自动注入,类名不能相同(即便包名不同),因为自动注入时,id与类名相同,所以如果两个类名一样的话,会因为Bean的id相同而报错。如果类名一定要相同的话,只能是其中一个类,手动加上注解并将名称改为其他。