Binding Annotation in spring

▼魔方 西西 提交于 2019-12-12 04:07:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!