zoukankan      html  css  js  c++  java
  • @AutoWired

    在springboot中启用了@SpringBootApplication注解,就能启用spring内建注解。包含@AutoWired。

    @AutoWired可标记到

    • 属性
    • setter
    • 构造器

    FooFormatter

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

    1、属性

    @SpringBootTest
    class AttrTests {
        @Autowired
        private FooFormatter fooFormatter;//可以将fooFormatter改成其他名字如:fooFormat,因为@AutoWired是byType的。
    。。。
    }

    2、setter

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

    3、构造器

    @SpringBootTest
    class ConstructorTests {
        private FooFormatter fooFormatter;
        @Autowired
        public ConstructorTests(FooFormatter fooFormatter) {
            this.fooFormatter = fooFormatter;
        }
    。。。
    }

    如果依赖的对象没有被注入,如

    @SpringBootTest
    class RequireTests {
        @Autowired
        private cn.hutool.core.lang.Dict dict;
        @Test
        void test() {
            if (dict == null) {
                System.out.println("空");
            }
        }
    
    }

    就会抛出异常:

    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.hutool.core.lang.Dict' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    因此,需要在@AutoWired后边的括号里加上required=false

    @Autowired(required = false)
    private Dict dict;

    执行后,就不会抛出异常了。

    但是,同一个接口有多个实现类时,如果在用@AutoWired就无法确认到底用的是哪个类了。解决方法是加上@Qualifier。见下一篇。

  • 相关阅读:
    Google Chrome 自定义协议(PROTOCOL)问题的处理
    C# 6.0/7.0 的新特性
    MySQL 5.7.18 压缩包版配置记录
    nginx.conf文件内容详解
    博客添加动态动漫妹子
    TypeScript 3.8beta版
    微信浏览器H5开发常见的坑
    Babel7知识梳理
    雅虎前端优化35条规则
    webpack
  • 原文地址:https://www.cnblogs.com/yaoyuan2/p/11745339.html
Copyright © 2011-2022 走看看