Annotation Injection & XML Injection
1. Which is better?
2. Namespace for annotation
3. Context: component-scan
- Use bean :
- Register bean :
- @Autowired
Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.
- Constructors
public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}
- Setter methods
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
- Fields
public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
@Autowired
private MovieCatalog movieCatalog;
// ...
}
- @Bean
@Bean Methods in @Configuration Classes
Typically, @Bean methods are declared within @Configuration classes. In this case, bean methods may reference other @Bean methods in the same class by calling them directly. This ensures that references between beans are strongly typed and navigable. Such so-called 'inter-bean references' are guaranteed to respect scoping and AOP semantics, just like getBean() lookups would. These are the semantics known from the original 'Spring JavaConfig' project which require CGLIB subclassing of each such configuration class at runtime.
As a consequence, @Configuration classes and their factory methods must not be marked as final or private in this mode.
For example:
@Configuration public class AppConfig { @Bean public FooService fooService() { return new FooService(fooRepository()); } @Bean public FooRepository fooRepository() { return new JdbcFooRepository(dataSource()); } // ... }
@Bean Lite Mode
@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain oldclass. In such cases, a @Bean method will get processed in a so-called 'lite' mode. In contrast to the semantics for bean methods in @Configuration classes, 'inter-bean references' are not supported in lite mode.
For example:
@Component public class Calculator { public int sum(int a, int b) { return a+b; } @Bean public MyBean myBean() { return new MyBean(); } }
- @Component
- @Required
public class SimpleMovieLister {
private MovieFinder movieFinder;
@Required
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}
- @Repository