@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。见下一篇。

原文地址:https://www.cnblogs.com/yaoyuan2/p/11745339.html