Reputation: 702
I have learnt that autowiring a bean is actually not a good practice. This is also mentioned in the spring document. I know that there are two types of bean configuration. One is by XML config, another is by java configuration class. If we want to use code to do bean configuration and not using @autowired, how can we do that? It seems like if using code, we will still need @autowired in order to inject the bean?
e.g. in the following, if we want to not using @Autowired, how can we do that? and what should be the best practice?
@Service
public class ClassA {
private ClassB classB;
@Autowired
public ClassA(ClassB classB) {
this.classB = classB;
}
}
Upvotes: 5
Views: 10185
Reputation: 2571
It is best to use a constructor dependency injection if possible because constructor injection prevents you from circular dependencies and makes testing easier.
Using Lombok
@Service
@RequiredArgsConstructor
public class ClassA {
private final ClassB classB;
}
No lombok
@Service
public class ClassA {
private final ClassB classB;
public ClassA(ClassB classB) {
this.classB = classB;
}
}
However, setter injection works as well. Look at more answers here.
Upvotes: 7
Reputation: 2572
Where have you read that autowiring is bad practice? Autowiring is automatic dependency injection - the core function of Spring.
I think you've read that field injection like this is bad practice because it for instance makes mocking out dependencies for testing impossible:
@Service
public class ClassA {
@Autowired
private ClassB classB;
}
In newer Spring versions you can omit the @Autowired annotation on the constructor if the class only have one constructor.
Upvotes: 14
Reputation: 195
One option would be to use a @Configuration class with @Bean methods within. Something like this.
@Configuration
public MyConfigClass {
@Bean
ClassB makeClassB(){
return new ClassB();
}
@Bean
ClassA makeClassA(final ClassB classB){
return new ClassA(classB);
}
}
Please be aware that if a @Component class has a single constructor it is, by default, annotated with @Autowired. This may help to explain why it sometimes seems to work but you cannot see any injection.
Upvotes: 2