|
| 1 | +package ioc.question_008; |
| 2 | + |
| 3 | +import ioc.commun.Person; |
| 4 | +import ioc.question_004.MyConfiguration; |
| 5 | +import ioc.question_008.dao.MyDaoRepository; |
| 6 | +import ioc.question_008.dao.dao; |
| 7 | +import ioc.question_008.service.MyService; |
| 8 | +import ioc.question_008.service.service; |
| 9 | +import org.springframework.context.annotation.AnnotationConfigApplicationContext; |
| 10 | +import org.springframework.context.annotation.ComponentScan; |
| 11 | +import org.springframework.context.annotation.Configuration; |
| 12 | +import org.springframework.context.annotation.Import; |
| 13 | + |
| 14 | +/** |
| 15 | + * Can you describe: |
| 16 | + * 1-Dependency injection using Java configuration? |
| 17 | + * 2-Dependency injection using annotations (@Autowired)? |
| 18 | + * 3-Component scanning, Stereotypes? |
| 19 | + * 4-Scopes for Spring beans? What is the default scope? |
| 20 | + * |
| 21 | + * 1-Java configuration: |
| 22 | + * @Bean the annotated method will produces a bean that will be managed by the container. |
| 23 | + * @Configuration indicates that the annotated class contains one or more methods annotated by @Bean. |
| 24 | + * 2,3- (@Component, @Autowired) |
| 25 | + * @Component indicate that the annotated class can be automaticaly detected and registred as a @Bean in the |
| 26 | + * application context. |
| 27 | + * @Autowired indicated that the container should look for a bean and inject it in the annoted place. |
| 28 | + * @ComponentScan define a root package that should be scanned to create @Bean. |
| 29 | + * |
| 30 | + * Some stereotype : |
| 31 | + * @Component: Root annotation, uses as a componenet scan condidate. |
| 32 | + * @Service: Business logic. |
| 33 | + * @Repository: Data access logic. |
| 34 | + * @Controller: Web Controller class. |
| 35 | + * @Configuration: Class that declare beans to be loaded and managed by the container. |
| 36 | + * |
| 37 | + */ |
| 38 | + |
| 39 | +@Configuration |
| 40 | +@Import(MyConfiguration.class) |
| 41 | +@ComponentScan(basePackageClasses = {MyDaoRepository.class, MyService.class} ) |
| 42 | +public class DependencyInjection { |
| 43 | + |
| 44 | + public static void main( String[] args ) { |
| 45 | + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DependencyInjection.class); |
| 46 | + dao myDaoRepository = (MyDaoRepository) context.getBean("myDaoRepository"); |
| 47 | + service myService = (service) context.getBean("myService"); |
| 48 | + System.out.println(myDaoRepository); |
| 49 | + Person p = context.getBean(Person.class); |
| 50 | + myService.save(p); |
| 51 | + System.out.println(myDaoRepository); |
| 52 | + myService.delete(p); |
| 53 | + System.out.println(myDaoRepository); |
| 54 | + |
| 55 | + |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments