7.4.5 Excluding a bean from autowiring

On a per-bean basis, you can exclude a bean from autowiring. In Spring’s XML format, set the autowire-candidate attribute of the <bean/> element to false; the container makes that specific bean definition unavailable to the autowiring infrastructure (including annotation style configurations such as @Autowired).

根据每个bean,你可以将一个bean从自动装配中排除.在Spring的XML格式中,设置 <bean/> 元素的 autowire-candidate 属性为 false;容器就会使得指定的bean定义无法从自动装配基础设施中获取到(包括注解样式的配置,例如 @Autowired).

The autowire-candidate attribute is designed to only affect type-based autowiring. It does not affect explicit references by name, which will get resolved even if the specified bean is not marked as an autowire candidate. As a consequence, autowiring by name will nevertheless inject a bean if the name matches.

 autowire-candidate 属性仅会影响基于类型的自动装配.它不会影响通过名称的明确引用,它会被解析即使它没有被标记为自动装配的候选者.就结果而言,如果名称匹配的话,通过名称的自动装配依然会注入bean.

You can also limit autowire candidates based on pattern-matching against bean names. The top-level <beans/> element accepts one or more patterns within itsdefault-autowire-candidates attribute. For example, to limit autowire candidate status to any bean whose name ends with Repository, provide a value of *Repository. To provide multiple patterns, define them in a comma-separated list. An explicit value of true or false for a bean definitions autowire-candidateattribute always takes precedence, and for such beans, the pattern matching rules do not apply.

你也可以通过模式匹配相对应的bean名称来限制自动装配候选者.顶级 <beans/> 元素会从它的default-autowire-candidates 属性中接收一个或多个模式.例如,限制自动装配候选者的状态,让它们的名称以Repository结尾,提供一个值为*Repository.提供多个模式,定义它们字一个逗号分隔的列表中.给bean定义 autowire-candidate属性一个明确的值 true 或false 总是最优先的,像这样的beans,就不会应用模式匹配规则.

These techniques are useful for beans that you never want to be injected into other beans by autowiring. It does not mean that an excluded bean cannot itself be configured using autowiring. Rather, the bean itself is not a candidate for autowiring other beans.

这个技术对于你不想通过自动装配注入到其他beans的beans很有用.它并不意味着被排除的bean不能够通过自动装配被配置.倒不如说,对于自动装配的其他beans,它不是一个候选者.

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/80940284