ITeye博客

3Spring使用annotation方式autowire

garrincha · 2014-08-27 11:54 · Spring入门 · 编程语言 · Markdown

之前讲了xml中的autowire,是在被注入的bean上写autowire=“byName”当然还可以byType,default等等。 当然autowire这句话可以放到annotation中,这样的好处是 1、xml中的bean特别的整洁,每一行写一个bean,没有bean之间相互注入的关系,没有autowire的补丁。 2、由于整洁,可以只让程序员只关注bean,而把关系放到annotation中,这样更有条理。bean负责生成类的实例,注入由annotation负责

需要用到上一个例子

使用xml的autowire

现在修改springbean.xml为下面这个样子


<?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/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">  
            <!-- 新增xml的命名空间,接下来会用到context标签 -->
            <!-- context对应的链接 -->
            <!-- context对应的xsd -->
            <context:annotation-config></context:annotation-config><!-- 表示使用annotation进行配置 -->
            
            <bean id = "dao" class="com.spring.dao.UserDao"></bean>
            <bean id="userService" class ="com.spring.service.UserService">
            </bean>        
</beans>

新增命名空间的配置。 xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd 新增了context:annotation-config</context:annotation-config>标签,表示使用注释的方式进行配置。 同时删除掉xml文件中userService bean的autowire的配置。

在UserService类setDao方法上面增加@Autowired


package com.spring.service;

import org.springframework.beans.factory.annotation.Autowired;

import com.spring.dao.UserDao;

public class UserService {

	private UserDao dao;
	public UserDao getDao() {
		return dao;
	}
	@Autowired
	public void setDao(UserDao dao) {
		this.dao = dao;
	}
	public void add()
	{
		dao.add();
	}
	
}

测试一下,还是不行,因为使用annotation需要导入一个jar包 现在导入common-annotations.jar 导入后入下图。

再测试一下,就ok了

从现在起都提供源代码以供参考。请自行下载源码吧

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。