Dims
Dims

Reputation: 50999

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?

What is conventional way to inject beans into one configuration from another one? Is it possible to refer bean by name and not use @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
MyDependentBean myDependentBean() {
   MyDependentBean ans = new MyDependentBean();
   ans.setProperty( mySeparateConfig.myNamedBeanInDifferentConfig() );
   return ans;
}

Configs are of different classes by definition.

Upvotes: 1

Views: 285

Answers (1)

Duncan
Duncan

Reputation: 717

Actually, there are several ways to inject bean by annotation.

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

@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. I think it's dangerous to autowire by type. Hope this would help you.

Upvotes: 1

Related Questions