Just migrating from xml based config to java based config in Spring 4.3.
In xml we had
<beans ... default-autowire="byName">
<component-scan .../>
...
</beans>
On Java classes we have no #Autowired annotations on fields:
#Component
public class MyService {
private OtherService otherService;
// +setters
....
}
Previously in xml With the default-autowire="byName" autowiring worked pretty well.
Now when moving to JavaConfig I cannot find a way to enable the default autowire mechanism for component scanning.
With autowire by name the wiring works without a #Autowired annotation.
With #Bean(autowire=BY_NAME) i can define a bean to autowire by name, but I would need that mechanism for component scanning. Not to define all beans with #Bean factory method.
Also I try not to add #Autowired annotations to all fields across all classes. Thats just too much to change.
My question now is: How to tell component-scan to autowire found beans by name?
I don't know if I understand what you want to do, but Spring supports #Qualifier and #Resource annotations:
#Resource takes a name attribute, and by default Spring interprets that value as the bean name to be injected. In other words, it follows by-name semantics
One solution would be to update the bean definition with a BeanFactoryPostProcessor to mark all beans to autowire by name like:
public class AutowireScannedByNameBeanPostProcessor implements BeanFactoryPostProcessor {
#Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
Arrays.stream(beanFactory.getBeanDefinitionNames()).forEach(name -> {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
if (beanDefinition instanceof ScannedGenericBeanDefinition) {
((ScannedGenericBeanDefinition) beanDefinition).setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME);
}
});
}
}
I am still curious if there is a setting in spring that can do this.
Related
Taking as reference the post Spring #Autowired and #Qualifier
We have this example to fix the autowiring conflict :
public interface Vehicle {
public void start();
public void stop();
}
There are two beans, Car and Bike implements Vehicle interface.
#Component(value="car")
public class Car implements Vehicle {
#Override
public void start() {
System.out.println("Car started");
}
#Override
public void stop() {
System.out.println("Car stopped");
}
}
#Component(value="bike")
public class Bike implements Vehicle {
#Override
public void start() {
System.out.println("Bike started");
}
#Override
public void stop() {
System.out.println("Bike stopped");
}
}
#Component
public class VehicleService {
#Autowired
#Qualifier("bike")
private Vehicle vehicle;
public void service() {
vehicle.start();
vehicle.stop();
}
}
That's a very good example to fix this problem.
But when I have the same problem but without those balises in the application context:
<context:component-scan></context:component-scan>
<context:annotation-config></context:annotation-config>
All the issues are solved by using the #Qualifier annotation, but in my case we don't use the balise that permit to use annotation.
The question is :
How can I fix this issue just using the configuration in application context, that's it, without using annotations?
I searched a lot and I found people talking about autowire attribute in the bean declaration <bean id="dao" class="package.IDao" autowire="byName"></bean> and I need more explanation about it.
How can I fix this issue just using the configuration in application
context?
You could use the qualifier tag like below (see https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-autowired-annotation-qualifiers)
<context:annotation-config/>
<beans>
<bean class="your_pkg_route.Vehicle">
<qualifier value="bike"/>
</bean>
</beans>
</context:annotation-config>
I found people talking about autowire attribute in the bean
declaration and I need more explanation about it
Using Annotation
#Autowired used on a bean declaration method injects the defined dependencies by (another) declared beans. Now, if your dependencies are in the same context of your application, you don't need to use the #Autowired annotation at all because Spring is able to figure them out by itself. So, if your dependencies are outside your applicatoin context then you can use it.
For example, take as reference the below code:
#Autowired
#Bean
public MyBean getMybean(Dependency1 depdency1, Dependency2 depdency2) {
return new MyBean(depdency1.getSomeStuff(), depdency2.getSomeOtherStuff());
}
Here, #Autowired will find an instance of Dependency1 and Dependency2 and will provide them for the creation of an instance of MyBean.
Using xml configuration
From Pro Spring 5... Spring supports five modes for autowiring.
byName: When using byName autowiring, Spring attempts to wire each property to a bean of the same name. So, if the target bean has a property named foo and a foo bean is defined in ApplicationContext, the foo bean is assigned to the foo property of the target.
byType: When using byType autowiring, Spring attempts to wire each of the
properties on the target bean by automatically using a bean of the same type in
ApplicationContext.
constructor: This functions just like byType wiring, except that it uses constructors rather than setters to perform the injection. Spring attempts to match the greatest numbers of arguments it can in the constructor. So, if your bean has two constructors, one that accepts a String and one that accepts String and an Integer, and you have both a String and an Integer bean in your ApplicationContext, Spring uses the two-argument constructor.
default: Spring will choose between the constructor and byType modes
automatically. If your bean has a default (no-arguments) constructor, Spring uses
byType; otherwise, it uses constructor.
no: This is the default
So, in your case you would need to do something like this (BUT, I would NOT recommend it. Why?, you would need to declare Vehicle class as a bean and a component which is not correct, see Spring: #Component versus #Bean. On the other hand I'm not sure if you could use it just declaring it as a bean):
// xml config
<context:annotation-config/>
<beans>
// use the primary tag here too! in order to say this the primary bean
// this only works when there are only two implementations of the same interface
<bean id="bike" primary="true" class="your_pkg_route.Bike"/>
<bean id="car" class="your_pkg_route.Car"/>
<bean autowire="byName" class="your_pkg_route.VehicleService"/>
<beans>
</context:annotation-config>
// VehicleService
#Component
public class VehicleService {
private Vehicle bike; // call attribute 'bike' so it is autowired by its name
public void service() {
//...
}
}
As you can see there is a lot of complications trying to do this using xml config, so I would recommend you to use the annotation option if possible.
Related posts:
Why do I not need #Autowired on #Bean methods in a Spring configuration class?
Difference between #Bean and #Autowired
PS: I have not tested any of the posted codes.
You can use #Primary instead of #Qualifier
#Primary
#Component(value="bike")
public class Bike implements Vehicle {
we use #Primary to give higher preference to a bean when there are multiple beans of the same type.
We can use #Primary directly on the beans
You can also set primary attribute in XML:
property has primary attribute:
<bean primary="true|false"/>
If a #Primary-annotated class is declared via XML, #Primary annotation metadata is ignored, and is respected instead.
We can autowire by field, setter, constructor. But we can also define beans only in configuration class and not use autowire at all. What are advanatages of doing so? example config :
#Configuration
class DrawingConfiguration {
#Bean
DrawingFacade drawingFacade(DrawingRepository repository) {
DrawingFactory factory = new DrawingFactory();
return new DrawingFacade(repository, factory);
}
}
If you define a bean in a configuration file you still need to autowire it, but you don't need to annotate it with #Component/#Service/#Repository annotation. It is just way to say that this bean is a #Component.
I have a Spring Configuration class that looks like:
#Configuration
public class MyDependencyConfig {
#Bean
#Primary
public MyDependency getMyDependency(){
System.out.println("getMyDependency");
return Mockito.mock(MyDependency.class);
}
#Bean
public MyDependency getMyDependency2(){
System.out.println("getMyDependency2");
return Mockito.mock(MyDependency.class);
}
}
And have elsewhere in my code:
#Autowired
MyDependency foo
Why is it when the application context starts up, my console prints
getMyDependency
getMyDependency2
when only the bean from getMyDependency() will be used? I am using spring boot-1.5.1.RELEASE
Thank you kindly,
Jason
The Spring configuration instantiates and loads all declared and required beans in the Spring container at the startup of the Spring context.
So, even if you don't use all beans defined in your configuration, the methods annotated #Bean in your configuration will be all invoked.
The #Primary annotation has another goal.
It indicates that a bean should be given preference when multiple
candidates are qualified to autowire a single-valued dependency. If
exactly one 'primary' bean exists among the candidates, it will be the
autowired value.
It is just a way to not specify systematically the #Qualifier annotation when you have more than one candidate bean.
For example in your case as one of two beans is specified as primary :
#Bean
#Primary
public MyDependency getMyDependency(){
System.out.println("getMyDependency");
return Mockito.mock(MyDependency.class);
}
You don't need to specify the qualifier "getMyDependency" to inject which one specified as primary :
#Autowired
#Qualifier("getMyDependency")
MyDependency foo;
You can directly do that :
#Autowired
MyDependency foo;
While for the second one bean that is not specified as #Primary :
#Bean
public MyDependency getMyDependency2(){
System.out.println("getMyDependency2");
return Mockito.mock(MyDependency.class);
}
You have to specify #Qualifier to clear ambiguities when you want to inject it :
#Autowired
#Qualifier("getMyDependency2")
MyDependency foo;
Loading beans in a lazy way is not advised as it delays the catch of configuration errors. So, it is eager by default.
You have more details in the link provided in your comment.
Now, if you want to prevent this default behavior and define a lazy initialization for a bean, you can alternatively specify the lazy String value in the #Scope annotation of the bean :
#Bean
#Scope("lazy")
public MyDependency getMyDependency(){
...
}
or better you can annotate the bean declaration or all the configuration (if you want that all beans be lazy initialized) with a #Lazy annotation.
For a specific bean :
#Bean
#Lazy
public MyDependency getMyDependency(){
...
}
For all beans of the configuration :
#Lazy
#Configuration
public class MyDependencyConfig {
...
}
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.
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.
It seems not the case. I used to have the notion that XML configurations are meant to override annotations. But when I set autowire="no" in the XML configuration, the bean's #Autowired annotated property still takes effect. I'm no longer sure if XML autowire has anything to do with #Autowired anymore. It's quite counter-intuitive in my opinion.
Can someone point me to a documentation that says something about this?
Here's my example:
<bean class="com.example.Tester"></bean>
<bean class="com.example.ClassToTest" autowire="no"></bean>
public class Tester
{
#Autowired
ClassToTest testSubject;
}
public class ClassToTest
{
#Autowired // I want this not to get autowired without removing this annotation
private OtherDependency;
}
autowire="no" means we have to explicit wire our dependencies using either XML-based configuration or #Autowire and it is default setting.
Auto-wiring by xml configutaion or by annotation means implicitly mapping dependencies using given strategy.
For more details refer here