@Autowire默认模式

发布于 2024-11-01 17:13:46 字数 85 浏览 6 评论 0原文

Spring @Autowire beans 如何:byName 或 byType?如果不可能,是否使用另一种模式进行第二次试验?

How does Spring @Autowire beans: byName or byType? If one is not possible, is a second trial done using another mode?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

与酒说心事 2024-11-08 17:13:46

如果使用@Autowired进行注释,它将注入具有匹配类型的bean(如果存在多个类型,则会抛出异常)。要指定名称,请使用@Qualifier注释。

If annotated with @Autowired it will inject the bean with the matching type (An exception will be thrown if there are more than one of a type). To specify a name use the @Qualifier annotation.

隱形的亼 2024-11-08 17:13:46

Springs @Autowire 按类型连接。对于按名称接线,您还可以使用

@Resource(name = "id")

Springs @Autowire wires by type. For wiring by name you can also use

@Resource(name = "id")
划一舟意中人 2024-11-08 17:13:46

@Autowired 的默认模式是 byType

The default mode of the @Autowired is byType.

被你宠の有点坏 2024-11-08 17:13:46

变量或 setters 方法上的 Autowired 注释相当于 xml 属性 autowire="byType"

XML 属性 autowire 默认为 no

"no": 

The traditional Spring default. No automagical wiring. Bean references
must be defined in the XML file via the <ref/> element (or "ref"
attribute). We recommend this in most cases as it makes documentation
more explicit.

Autowired annotation on variable or setters method is equivalent to xml attribute autowire="byType"

XML attribute autowire is defaut as no

"no": 

The traditional Spring default. No automagical wiring. Bean references
must be defined in the XML file via the <ref/> element (or "ref"
attribute). We recommend this in most cases as it makes documentation
more explicit.
一页 2024-11-08 17:13:46

它们是 no、byName、byType、构造函数和自动检测。默认模式为 no,即默认情况下,在传统的基于 XML 的配置中自动装配是关闭的。

使用@Autowired注解-

1)在属性上使用@Autowired:

当在属性上使用@Autowired时,相当于在配置文件中通过byType进行自动装配。

2)属性setter上的@Autowired:

当@Autowired用在setter上时,也相当于配置文件中byType自动装配。

3)构造函数上的@Autowired:

当@Autowired用在bean的构造函数上时,也相当于配置文件中构造函数的自动装配。

使用 @Qualifier 解决依赖项解析中的冲突

正如我们所知,如果我们在 byType 模式下使用自动装配,并且依赖项会查找属性类类型。如果没有找到这样的类型,则会抛出错误。但是,如果同一类类型有两个或多个 bean 该怎么办?

在这种情况下,spring 将无法选择正确的 bean 来注入属性,您将需要使用限定符来帮助容器。

要使用限定符解析特定的bean,我们需要使用@Qualifier注释和@Autowired注释,并在注释参数中传递bean名称。

These are no, byName, byType, constructor, and autodetect. The default mode is no i.e. by default autowiring is turned off in traditional XML based configuration.

Using @Autowired annotation-

1) @Autowired on properties:

When @Autowired is used on properties, it is equivalent to autowiring by byType in configuration file.

2) @Autowired on property setters:

When @Autowired is used on setters, it is also equivalent to autowiring by byType in configuration file.

3) @Autowired on constructors:

When @Autowired is used on bean’s constructor, it is also equivalent to autowiring by constructor in configuration file.

Use @Qualifier for conflict in dependency resolution

As we learned that if we are using autowiring in byType mode and dependencies are looked for property class types. If no such type is found, an error is thrown. But, what if there are two or more beans for same class type.

In this case spring will not be able to choose correct bean to inject into property, and you will need to help the container using qualifiers.

To resolve a specific bean using qualifier, we need to use @Qualifier annotation along with @Autowired annotation and pass the bean name in annotation parameter.

匿名。 2024-11-08 17:13:46

我刚刚查看了 spring-beans-5.2.7.RELEASE.jar 的源代码。它包含类 DefaultListableBeanFactory 和方法,

@Nullable
    protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {
        Class<?> requiredType = descriptor.getDependencyType();
        String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
        if (primaryCandidate != null) {
            return primaryCandidate;
        }
        String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
        if (priorityCandidate != null) {
            return priorityCandidate;
        }
        // Fallback
        for (Map.Entry<String, Object> entry : candidates.entrySet()) {
            String candidateName = entry.getKey();
            Object beanInstance = entry.getValue();
            if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
                    matchesBeanName(candidateName, descriptor.getDependencyName())) {
                return candidateName;
            }
        }
        return null;
    }

正如我们所看到的,它尝试按类型自动装配。如果没有成功,它会尝试按此行中的名称自动装配

matchesBeanName(candidateName, descriptor.getDependencyName()))

I just checked out the source code of the spring-beans-5.2.7.RELEASE.jar. It contains class DefaultListableBeanFactory with the method

@Nullable
    protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {
        Class<?> requiredType = descriptor.getDependencyType();
        String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
        if (primaryCandidate != null) {
            return primaryCandidate;
        }
        String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
        if (priorityCandidate != null) {
            return priorityCandidate;
        }
        // Fallback
        for (Map.Entry<String, Object> entry : candidates.entrySet()) {
            String candidateName = entry.getKey();
            Object beanInstance = entry.getValue();
            if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
                    matchesBeanName(candidateName, descriptor.getDependencyName())) {
                return candidateName;
            }
        }
        return null;
    }

As we can see it tries to autowire by type. If no success it tries to autowire by name in this line

matchesBeanName(candidateName, descriptor.getDependencyName()))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文