spring注解配置

在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层表现层

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值