spring-依赖注入的注解配置

    xiaoxiao2026-04-25  11

    可以使用注解来代替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组件 @org.springframework.context.annotation. Scope 指定bean的作用域,取值有singleton(默认值)、prototype。可以放在@Component注解的上一行。 生成bean的命名规则: @Service //默认beanid为类名的小驼峰形式,即studentServiceImpl。 public class StudentServiceImpl{} @Service("studentService") //表明beanid为指定的名字studentService public class StudentServiceImpl{}

    1.2字段的注解

    @javax.annotation. Resource Spring直接用了java的标准注释。它与<Property />元素的ref属性有相同的结果。该注解可以放在setter方法前。 @  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;

    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 { @Resource RongzaiService dtService; @Resource QdListService qdListService; @Resource QdNhjService qdNhjService; @Resource QdDetailService qdDetailService; } //子类需要加注解 @Component public class PresaleMeetingplaceTask extends AbstractCDNTask {} //每个子类都需要加注解 @Component public class Double11Task extends AbstractCDNTask {}
    最新回复(0)