spring-依赖注入的注解配置

来源:互联网 发布:网络基站建设方案 编辑:程序博客网 时间:2024/05/16 23:38

可以使用注解来代替xml配置。

1.不同位置的注解

1.1 类的注解

@ org.springframework.stereotype.Component
一个类若标注了@Component,表明此类被作为Spring的Bean类。对象名默认为类名首字母小写。也可以@Component("name")来手动指定。
此外还有@Service、@Controller与@Repository。它们都有@Component的效果,只是为了方便人看,见名知意。
@org.springframework.stereotype.Service
用于标注业务层组件
@org.springframework.stereotype.Controller
用于标注控制层组件(如struts中的action)
@org.springframework.stereotype.Repository
用于标注数据访问组件,即DAO组件
以上四个注解可以放在abstract类上面。

@org.springframework.context.annotation.Scope
指定bean的作用域,取值有singleton(默认值)、prototype。可以放在@Component注解的上一行。

生成bean的命名规则
@Service//默认beanid为类名的小驼峰形式,即studentServiceImpl。public class StudentServiceImpl{}@Service("studentService")//表明beanid为指定的名字studentServicepublic class StudentServiceImpl{}

1.2字段的注解

@javax.annotation.Resource
Spring直接用了java的标准注释。它与<Property />元素的ref属性有相同的结果。
该注解直接标在字段(不能为static)上即可,该字段可以没有getter/setter方法,权限为private也没有关系
@ org.springframework.beans.factory.annotation.Autowired
大致等同于@Resource,这是spring自己的。
@Inject
大致等同于@ResourceJava,这是依赖注入规范,比@Resource要新。

注入bean的命名规则:
@Resource//student=context.getBean("student")Student student;@Resource(name="xiaoMing")//student=context.getBean("xiaoMing")Student student;@Resource//xiaoMing=context.getBean("xiaoMing")Student xiaoMing;

1.3 方法的注解

@ javax.annotation.PostConstruct
相当于xml配置中的init-method.
@javax.annotation.PreDestroy
相当于xml配置中的destroy-method.

2.xml配置的必要性

有些类是别人写好的,你没有机会在这些类的上面添加注解,那就需要用xml来配置了。

3.注解的自动扫描

<context:annotation-config>
Spring默认禁用注解,加上此标签才能启用。
它省掉了<propertiy>配置,但省不掉<bean>配置。

<context:component-scan  base-package="com.yichudu">
它省掉了<bean>配置。它用来递归地扫描这个包及子包下的注解。
一个beans.xml及bean及app代码示例见下。注意版本号要与jar对应。


过滤组件扫描
可以省略@Conponent注释。
<!--自动扫描派生于Instrument乐器类下的bean,这些bean不需要@Component注释 --><context:component-scan base-package="com.likeyichu.resource"><context:include-filter type="assignable" expression="com.likeyichu.resource.Instrument"/></context:component-scan>

4.抽象基类的注解

例子见下。
//抽象类上不加注解(似乎加注解也没关系),字段照常加注解。public abstract class AbstractCDNTask implements SimpleJobProcessor {@ResourceRongzaiService dtService;@ResourceQdListService qdListService;@ResourceQdNhjService qdNhjService;@ResourceQdDetailService qdDetailService;}//子类需要加注解@Componentpublic class PresaleMeetingplaceTask extends AbstractCDNTask {}//每个子类都需要加注解@Componentpublic class Double11Task extends AbstractCDNTask {}


0 0