---
title: "4Spring自动装配——annotation resource方式"
author: "garrincha"
date: "2014-08-27T17:40:48Z"
tags: ["Spring", "annotation", "resource", "注释", "自动装配"]
categories: ["编程语言"]
slug: "4spring-annotation-resource"
draft: false
lastmod: "2014-08-27T17:40:48Z"
id: 2109688
url: "https://garrincha.iteye.com/blog/2109688"
---

对于自动装配的认识，经历了几个步骤
1手工配置xml
2在xml中配置bean，bean之间的注入关系用autowire
3不在xml中写autowire，写在annotation中
4干脆xml中一个bean也不写，bean和注入关系都挪到annotation中指定。
书接上回

[使用注释进行autowire](/admin/blogs/2109488)
上一讲用的注释的autowire，xml里面配置bean。
还是有一些麻烦，如果能不用配置bean，让spring自动扫描工程中（确切的说是给定包的位置）的类，然后把类自动实例化成bean，然后再根据类型或者名字的规则装配起来就更好了。
也就是说我们要达到这个效果，在上一讲的基础上，把xml中关于bean的配置也删除掉，并实现相同的效果。

0、先解释一下这次要用到的几个新注释
@Resource   放在set方法之上，表明这个地方需要注入对象（必须用component标注的类的对象）.
@Component 放在类的声明上面，表明这是一个需要实例的对象，并给出对象的名字。用法见例子
1、首先修改UserService类

```java

package com.spring.service;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.spring.dao.UserDao;

@Component("userService") 
//这里的userService的名字会在
//UserService service = (UserService) ctx.getBean("userService");
//中用到
public class UserService {

	private UserDao dao;
	public UserDao getDao() {
		return dao;
	}
	@Resource
	//表示这里需要注入对象
	public void setDao(UserDao dao) {
		this.dao = dao;
	}
	public void add()
	{
		dao.add();
	}
}


```


解释一下：类定义的上面用@Component注释表明这个类是需要实例化对象的，类似于在xml中定义了一个userService的bean。
@Resource表明这个地方需要注入对象，类似于在xml中用ref来表示注入的对象。
<span style="color:red">注意：同xml模式一样，被注入的对象必须实例化，也就是说被注入的UserDao这个类也需要加上@Component标签</span>
2、修改UserDao类如下

```java

package com.spring.dao;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component("dao")//UserDao实例化的对象名dao，用于之后的注入
public class UserDao {

	public void add()
	{
		System.out.println("执行UserDao.add（）方法");
	}
}

```

3、这两个地方修改之后，相当于autowire模式下在xml中写了2个bean。之后的装配工作由spring完成。开始测试吧
4、测试。测试代码不变

```java

package com.spring.service.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.service.UserService;
public class UserServiceTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		ApplicationContext ctx =new ClassPathXmlApplicationContext("springbeans.xml");
		UserService service = (UserService) ctx.getBean("userService");
		service.add();
	}

}

```


测试结果如下

```java

2014-8-27 17:34:10 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@30e3c624: display name [org.springframework.context.support.classpathxmlapplicationcontext@30e3c624]; startup date [wed aug 27 17:34:10 hkt 2014]; root of context hierarchy
2014-8-27 17:34:10 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [springbeans.xml]
2014-8-27 17:34:10 org.springframework.context.support.ClassPathXmlApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.classpathxmlapplicationcontext@30e3c624]: org.springframework.beans.factory.support.DefaultListableBeanFactory@2cc22a3b
2014-8-27 17:34:10 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@2cc22a3b: defining beans [dao,userservice,org.springframework.context.annotation.internalcommonannotationprocessor,org.springframework.context.annotation.internalautowiredannotationprocessor,org.springframework.context.annotation.internalrequiredannotationprocessor]; root of factory hierarchy
执行UserDao.add（）方法

```


<span style="color:red">一点其他
这里的注释@component可以改写为@Repository、@Service 和 @Controller，在具体使用中无差别，主要是为了从名字中识别这个被装配的组件在系统中的作用，仅此而已。