在spring学中,了解到配置方式有xml配置和注解配置两种,相比之下,注解配置比xml配置的效率较低,但是在很多情况下,注释配置比 XML 配置更受欢迎,因为它在代码编辑方面较简单,于是注释配置有进一步流行的趋势,下面就来简单的描述一下spring注解配置的简单过程:
1.copy命名空间,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="包名"></context:component-scan>
</beans>
2.在各个类的上面写:@Component("类名首字母小写")
3.在相应的属性上面写:@Resource(name="需要注入的bean")通过@resource注解把一个bean注入到当前的类中
例如:
一个类为DocumentManager :
@Component("documentManager")
public class DocumentManager {
@Resource(name="excelDocument")
private Document document;
public void read(){
this.document.readDocument();
}
public void write(){
this.document.writeDocument();
}
}
另一个类为ExcelDocument:
@Component("excelDocument")
public class ExcelDocument{
public void readDocument() {
System.out.println("excel read");
}
public void writeDocument() {
System.out.println("excel write");
}
}
注:
1.上述内容使用了类扫描机制的做法,配置文件中的配置很简单,但是注解配置的效率却较低
2.@Compnent的细化有以下三个,分别对应相应的层级:
@Repository dao层持续化层
@Service service层服务层
@Controller action层表现层