首先使用注解,需要有spring-aop-4.2.2.RELEASE.jar 这个jar包。
然后我们的bean.xml文件的约束也需要改动一下,并添加上这句话:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<context:component-scan base-package="com.dimples"></context:component-scan>
</beans>
指定了 base-package 以后,它会去这个包及其子包下找生成bean的注解。
然后对应的类我们这么写:
@Component(value="cust")
public class CustomerServiceImpl implements ICustomerService {
@Autowired
@Qualifier("custDaoImpl")
//@Resource(name="custDaoImpl2")
private ICustomerDao cust;
@Override
public void saveCustomer() {
cust.saveCustomer();
}
}
解析:@Componet就是生成bean的注解符号,其中的value可以不写,会有默认值,默认值为当前类的短名首字母小写,如本类就是customerServiceImpl。由此衍生的三个注解还有(作用都是一模一样的):
@Controller 一般用于表现层注解
@Service 一般用于业务层
@Repository 一般用于持久层
如果需要注入属性呢?我们知道属性注入有三种:
基本类型和String:我们采用 @Value 即可解决
集合类型:无法用注解注入
其他类型:还是上面那个service类,对其中的cust属性进行注入,我们有几种方式:
只使用@Autowired(自动装配),会去查找ICustomerDao类型,一个都找不到失败,查到唯一匹配的类型则成功,查到多个匹配此类型的时候,会拿属性名cust去跟那些类的beanid做匹配,若有匹配则成功,若无匹配则失败。
@Qualifier(获取资格的人)
这个标签如果使用,必须是跟在@Autowired后面的。它的含义是,如果@Autowired还没注入成功,再用这个指定的beanid去查找对应的bean并注入。
@Resource
如果明确知道了beanid,那么直接使用这个注入就好了!
用法上面的service类已经有了,不再赘述!
再有的就是关于bean的作用范围的标签,相当于xml中的scope属性:@Scope(value=""),取值也是那五个。
最后再说一句,注解和XML选择问题:当配置需要频繁修改的时候,用配置文件,因为不用改源码。如果碰到注解解决不了的配置的时候,例如注入复杂类型数据的时候,用XML文件。如果像Hibernate里有几百个实体类的时候,建议用注解,因为不然又要多维护几百个配置文件。