简体   繁体   English

为什么按类@Autowired 电线?

[英]Why @Autowired wires by class?

If each bean has name, and we have getBean() method, which receives bean name and in XML config we are also injecting beans by name, then why in Java config we are limited to @Autowired annotation which wires by class?如果每个 bean 都有名称,并且我们有getBean()方法,它接收 bean 名称,并且在 XML 配置中我们也按名称注入 bean,那么为什么在 Java 配置中我们仅限于按类连接的@Autowired注释?

What is conventional way to inject beans into one configuration from another one?将 bean 从另一种配置注入一种配置的常规方法是什么? Is it possible to refer bean by name and not use @Qualifier ?是否可以按名称引用 bean 而不是使用@Qualifier

UPDATE更新

I found a way to autowire by name between configurations.我找到了一种在配置之间按名称自动装配的方法。

First I autowire entire configuration by class:首先,我按类自动装配整个配置:

@Autowired
MySeparateConfig mySeparateConfig;

Then I just call instantiation method from that bean:然后我只是从那个 bean 调用实例化方法:

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

Configs are of different classes by definition.根据定义,配置属于不同的类。

Actually, there are several ways to inject bean by annotation.实际上,通过注解注入bean的方式有很多种。

given that we have this bean鉴于我们有这个豆

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

and in java class we can use following ways to inject it as far as I know在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;

or use spEL或使用拼写

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

However, I don't know the reason why spring autowired default is by type, either, and also wondering why.但是,我也不知道 spring 自动装配默认值是按类型的原因,也想知道为什么。 I think it's dangerous to autowire by type.我认为按类型自动装配很危险。 Hope this would help you.希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM