• SpringMVC:学习笔记(11)——依赖注入与@Autowired


    SpringMVC:学习笔记(11)——依赖注入与@Autowired 

    使用@Autowired

      从Spring2.5开始,它引入了一种全新的依赖注入方式,即通过@Autowired注解。这个注解允许Spring解析并将相关bean注入到bean中。

    使用@Autowired在属性上

      这个注解可以直接使用在属性上,不再需要为属性设置getter/setter访问器。

    @Component("fooFormatter")
    public class FooFormatter {
     
        public String format() {
            return "foo";
        }
    }
    

      在下面的示例中,Spring在创建FooService时查找并注入fooFormatter

    @Component
    public class FooService {
         
        @Autowired
        private FooFormatter fooFormatter;
     
    }

    使用@Autowired在Setters上

      @Autowired注解可用于setter方法。在下面的示例中,当在setter方法上使用注释时,在创建FooService时使用FooFormatter实例调用setter方法:

    public class FooService {
     
        private FooFormatter fooFormatter;
     
        @Autowired
        public void setFooFormatter(FooFormatter fooFormatter) {
                this.fooFormatter = fooFormatter;
        }
    }
    

      这个例子与上一段代码效果是一样的,但是需要额外写一个访问器。

    使用@Autowired 在构造方法上

      @Autowired注解也可以用在构造函数上。在下面的示例中,当在构造函数上使用注释时,在创建FooService时,会将FooFormatter的实例作为参数注入构造函数:

    public class FooService {
     
        private FooFormatter fooFormatter;
     
        @Autowired
        public FooService(FooFormatter fooFormatter) {
            this.fooFormatter = fooFormatter;
        }
    }  

    补充:在构造方法中使用@Autowired,我们可以实现在静态方法中使用由容器管理的Bean

    @Component
    public class Boo {
    
        private static Foo foo;
    
        @Autowired
        private Foo foo2;
    
        public static void test() {
            foo.doStuff();
        }
    }

    使用@Qualifier取消歧义

      定义Bean时,我们可以给Bean起个名字,如下为barFormatter

    @Component("barFormatter")
    public class BarFormatter implements Formatter {
     
        public String format() {
            return "bar";
        }
    }
    

      当我们注入时,可以使用@Qualifier来指定使用某个名称的Bean,如下:

    public class FooService {
         
        @Autowired
        @Qualifier("fooFormatter")
        private Formatter formatter;
     
    }

    参考链接:

  • 相关阅读:
    android apk 反编译
    js 读 xml 非ie 可以支持 chrome 浏览器 与 android webView
    php+mySQl 环境搭建
    Activity 生命周期
    div 隐藏 显示 占空间 不占空间
    android 异步加载
    android 文件操作
    透明 GridView 背景透明
    eclipse 版本理解
    WebKit 上的JS直接使用Java Bean
  • 原文地址:https://www.cnblogs.com/MrSaver/p/10888889.html
Copyright © 2020-2023  润新知