Spring的Annotation配置方法
手动配置Spring的bean是一件极为头疼的事情,工作量大不说,还特别容易写错,Annotation标签很好的解决了这个问题,会帮我们剩下很多时间,接下来就是配置的方法:
第一步:添加common-annotations.jar包;
第二步:引入对应的命名空间及对应的Schema文件地址:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><!-- 扫描标记了注解的类 --><context:annotation-config /><context:component-scan base-package="com.mossad" /></beans>

@Resourceprivate StockService stockService;也可以通过设置name属性来指定注入bean的名称,如下所示,此时注入的bean就是abcService而不是stockService了
@Resource("abcService")private StockService stockService;它还有一个属性是type,用来指定bean的类型,如果不设置,那么Spring会通过反射获取field的类型,然后查找相同类型的bean进行注入,如果多余一个则会抛出异常。@Autowired@Qualifier("stockService")private StockService stockService;