zoukankan      html  css  js  c++  java
  • 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;
     
    }

    参考链接:

  • 相关阅读:
    Django使用manage.py test错误解决
    Notepad++的find result窗口恢复
    qrcode 配套 PIL 或者 Image + ImageDraw
    pymssql.OperationalError: (20017 问题解决
    ConfigParser使用:1.获取所有section为list,2.指定section具体值,并转换为dict
    selenium&Firefox不兼容问题:Message: Unable to find a matching set of capabilitie;Can't load the profile. Profile;Message: 'geckodriver' executable needs to be in PATH
    使用宏实现透视表部分功能,将AB列数据合并统计.
    反射
    类的多态
    封装
  • 原文地址:https://www.cnblogs.com/MrSaver/p/10888889.html
Copyright © 2011-2022 走看看