【问题标题】:Why @Autowired wires by class?为什么@Autowired 按课程分类?
【发布时间】:2016-05-30 09:15:05
【问题描述】:

如果每个 bean 都有名称,并且我们有 getBean() 方法,它接收 bean 名称,并且在 XML 配置中我们也按名称注入 bean,那么为什么在 Java 配置中我们仅限于 @Autowired 注释,它按类连接?

将 bean 从另一种配置注入一种配置的传统方法是什么?是否可以按名称引用bean而不使用@Qualifier

更新

我找到了一种在配置之间按名称自动装配的方法。

首先我按类自动装配整个配置:

@Autowired
MySeparateConfig mySeparateConfig;

然后我只是从那个 bean 调用实例化方法:

@Bean
MyDependentBean myDependentBean() {
   MyDependentBean ans = new MyDependentBean();
   ans.setProperty( mySeparateConfig.myNamedBeanInDifferentConfig() );
   return ans;
}

根据定义,配置属于不同的类。

【问题讨论】:

  • 您不必使用@Autowired 进行注射。您可以在 context.xml 中定义您的 bean,并让 bean 通过<property> 标签进行交互。 <property name="blabla" ref="blablaref"> 在 bean 定义标签内。
  • @cihanseven 您的陈述是正确的,但问题是为什么@Autowire 在连接依赖关系时默认为按类?
  • 你有多少次拥有两个相同类但 id 不同的 bean?
  • @biziclop 我不是在寻找妻子,我在寻找理解。如果 bean 总是(或几乎总是)不同的类型,那么为什么我们在 XML 中按名称连接?
  • @Dims XML 是更古老的配置 Spring 的风格,这就是最初存在的一切。然后人们意识到很多 XML 配置是多余的,充满了<bean id="Foo" class="com.foo.Foo"/> 类型定义,所以当 Java 引入注解时,实现了自动装配以节省大部分样板配置。 XML 配置对于确实需要多个相同类型的 bean 的情况仍然有用。

标签: java spring


【解决方案1】:

其实通过注解注入bean有几种方式。

假设我们有这个 bean

<bean id="standardPasswordEncoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder" />

据我所知,在 java 类中我们可以使用以下方式注入它

@Autowired  // by type
StandardPasswordEncoder standardPasswordEncoder;

@Autowired
@Qualifier("standardPasswordEncoder")  // by bean id
StandardPasswordEncoder standardPasswordEncoder;

javax.annotation.@Resource  // by bean id
StandardPasswordEncoder standardPasswordEncoder;

javax.inject.@Inject  // by type
StandardPasswordEncoder standardPasswordEncoder;

或使用 spEL

@Value(#{standardPasswordEncoder})  // by bean id
StandardPasswordEncoder standardPasswordEncoder;

但是,我也不知道 spring autowired 默认是按类型的原因,也想知道为什么。我认为按类型自动接线很危险。希望这会对你有所帮助。

【讨论】:

  • “按类型自动接线很危险”?任何需要匹配字符串标识符(或更糟糕的是,变量名)的自动装配都会使无辜的重构成为潜在的灾难性事件,从而更加危险。
  • 是的,我同意你的观点,javax.annotation.Resource 更危险。但是,当谈到 spEL 和 Qualifier 时,我认为哪个 bean 是连线的要清楚得多。它不依赖于变量名,而只依赖于 bean id。并且当有相同类型的bean时出现异常的可能性较小。
猜你喜欢
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多