Spring Annotation(IOC篇)

Jul 28 2009

首先在application_context的xml配置文件中加入

<context:component-scan base-package="org.bean"/>

而且保证xml的schema中包括context名称空间。
@Component

//例如
@Component("member")
public class Member {
   private String id;
   }

这个Annotation主要用来定义bean。
@Service,@Controller,@Repository
这3个目前与@component同意,以后版本会细化。
@Autowired

//例如
@Component("member")
public class Member {
   private String id;
   @Autowired
   private Project project;
   }

这个Annotation主要用来自动查找context,并且关联其中的bean。
@Qualifier

@Component("member")
public class Member {
   private String id;
   private String name;
   @Autowired
   @Qualifier("project")
   private Project project;
   }

这个Annotation主要用来自动关联时的微调
@Scope

    @Scope("singleton")
    @Component("member")
    public class Member {
        private String id;
        private String name;
        @Autowired
        @Qualifier("project")
        private Project project;
        }

这个Annotation用来指定bean作用域与生成状态,默认为singleton,其他还有prototype(多个实例),request,session,global session,这3个是用在基于Spring ApplicationContext的Web项目。
在bean中我们已经看到了最基本的使用Java annotation的方式了,但是Spring对于Annotation还存在一些问题,比如:@Autowired同样可以应用于Collection中,比如List中。但是如果在List的属性中加上这个Annotation,那么通过容器初始化的bean会自动往 List中存放一个通过@Autowired自动查找出来的对象,这么做我也很难说它不对,但是还是感觉怪怪的。希望大家注意。
另外谈一下自动检测组件名称的方式(针对于@Component,@Service,@Controller,@Repository):如果给组件命名了,则按照这个名称注册到BeanFactory中,如果没有命名,则把小写开头的类名注册为组件名称。

@Component("project")
public class MyProject {
//......
}

如果是@Component,那么在ApplicationContext或者BeanFactory中注册的Bean名称是”myProject”,如果是@Component(“project”),则注册的Bean名称是”project”。
@Resource

    @Resource
    public void setOwner(Member owner) {
        this.owner = owner;
    }

或者

    @Resource(name="member")
    public void setOwner(Member owner) {
        this.owner = owner;
    }

其中特别之处在于@Resource如果加载属性或者setter之上,则按照属性名或者根据setter名称得到bean名称查找,如果找不到则按照类型查找。如果给@Resource加了name属性,则相当于按照这个名称查找,这种方式查找的优先级最高。

No responses yet

Leave a Reply