问题
We are using guice for dependency injection. Now we want to write new project using spring boot. Since we are using Spring Boot, we think it is better to use Spring for dependency injection instead of guice.
In guice we used Binding Annoation. This is very useful if we have multiple beans available and it can be injected according the annotations.
Similar to that what we have in Spring? Do we need to name the bean accordingly and use it with @Autowire
and @Qualifier
?
回答1:
You can use
@Autowired
when you have one bean of some type.
@Autowired
private MyBean myBean;
For many beans example configuration class:
@Configuration
public class MyConfiguration {
@Bean(name="myFirstBean")
public MyBean oneBean(){
return new MyBean();
}
@Bean(name="mySecondBean")
public MyBean secondBean(){
return new MyBean();
}
}
@Autowired
with @Qualifier("someName")
when you have more than one bean of some type and you want some specific.
@Autowired
@Qualifier("myFirstBean")
private MyBean myFirstBean;
@Autowired
@Qualifier("mySecondBean")
private MyBean mySecondBean;
When you want inject all beans of the same type you can:
@Autowired
private List<MyBean> myBeans;
回答2:
First hand example:
public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
private MovieCatalog movieCatalog;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
This is a question asking for the very basics concepts of Spring Framework, namely beans and dependancy injection.
What I would propose is to run one of sample sample projects like kickstart-sample and get yourself familiar with Spring while playing with code.
Then jumping to official docs for reference would be not bad either. Because there are more options to be aware when using annotations.
http://docs.spring.io/spring/docs/4.3.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#beans-autowired-annotation
来源:https://stackoverflow.com/questions/36262825/binding-annotation-in-spring