Ioc Container(DI)
reference:
https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html
def:objects define their dependencies only through constructor arguments
- org.springframework.beans
- org.springframework.context
A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.
Container Overview
configuring metadata
xml based
this bean definition corresponds to the actual objects
- service layer
- data access objects
annotation based
java-based
instantiating a Container
1 | ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml"); |
service.xml
1 | <?xml version="1.0" encoding="UTF-8"?> |
Dependency
- constructor-based Dependency
- setter-based
Annotation-based
@Required for setter method | @Autowired for constructor
1 | public class MovieRecommender { |
As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean defines only one constructor to begin with. However, if several constructors are available, at least one must be annotated to teach the container which one to use.
traditional constructor
1
2
3
4
5
6
7
8
9
10
11public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}setter
1
2
3
4
5
6
7
8
9
10
11public class SimpleMovieLister {
private MovieFinder movieFinder;
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}arbitrary names and multiple arguments
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class MovieRecommender {
private MovieCatalog movieCatalog;
private CustomerPreferenceDao customerPreferenceDao;
public void prepare(MovieCatalog movieCatalog,
CustomerPreferenceDao customerPreferenceDao) {
this.movieCatalog = movieCatalog;
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}fileds
1
2
3
4
5
6
7
8
9
10
11
12
13
14public class MovieRecommender {
private final CustomerPreferenceDao customerPreferenceDao;
private MovieCatalog movieCatalog;
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
this.customerPreferenceDao = customerPreferenceDao;
}
// ...
}arrays and collections
1
2
3
4
5
6
7
8
9
10
11public class MovieRecommender {
private Set<MovieCatalog> movieCatalogs;
public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
}map
1
2
3
4
5
6
7
8
9
10
11public class MovieRecommender {
private Map<String, MovieCatalog> movieCatalogs;
public void setMovieCatalogs(Map<String, MovieCatalog> movieCatalogs) {
this.movieCatalogs = movieCatalogs;
}
// ...
}
autowiring fails when no matching candiate beans are available
AOP
Aspect Oriented Programming