上QQ阅读APP看书,第一时间看更新
How to do it...
Let us create beans inside a JavaConfig's context definition class:
- Inside the ch02-jc\src\main\java directory, create a package: org.packt.starter.ioc.model. Implement the same Employee and Department model classes as in the previous recipe, Managing the beans in a XML-based container recipe. Open BeanConfig context definition class and inject these newly created Employee and Department beans in the container:
@Configuration public class BeanConfig { @Bean(name="empRec1") public Employee getEmpRecord1(){ Employee empRec1 = new Employee(); return empRec1; } @Bean(name="dept1") public Department getDept1(){ Department dept1 = new Department(); return dept1; } }
- To pass actual values and object references to the beans, we programmatically use the setters as one of the approaches for dependency injection. Add the following modifications to BeanConfig:
@Bean(name="empRec2") public Employee getEmpRecord2(){ Employee empRec2 = new Employee(); empRec2.setFirstName("Juan"); empRec2.setLastName("Luna"); empRec2.setAge(50); empRec2.setBirthdate(new Date(45,9,30)); empRec2.setPosition("historian"); empRec2.setSalary(100000.00); empRec2.setDept(getDept2()); return empRec2; } @Bean(name="dept2") public Department getDept2(){ Department dept2 = new Department(); dept2.setDeptNo(13456); dept2.setDeptName("History Department"); return dept2; }
- Another approach is to use the overloaded constructor for the dependency injection. Add the following modifications to BeanConfig:
@Bean(name="empRec3") public Employee getEmpRecord3(Department dept2){ Employee empRec1 = new Employee("Jose","Rizal", new Date(50,5, 19), 101, 90000.00, "scriber", getDept3()); return empRec1; } @Bean(name="dept3") public Department getDept3(){ Department dept3 = new Department(56748, "Communication Department"); return dept3; }
- Inside the package org.packt.starter.ioc.model.test in src\test\java, create a TestBeans class that will instantiate the ApplicationContext container using org.springframework.context.annotation.AnnotationConfigApplicationContext and will fetch all the beans using the familiar method getBean():
public class TestBeans { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(BeanConfig.class); System.out.println("--Result by Setter based Dependency Injection--"); context.refresh(); Employee empRec1 = (Employee) context.getBean("empRec1"); //refer to sources context.registerShutdownHook(); } }
Before invoking the getBean() overloads, pass the first BeanConfig definition to AnnotationConfigApplicationContext through context.register(). Then call context.refresh() to load all the registered beans to the container since we do not have the ApplicationServer yet to trigger the container loading. Finally, all objects are ready to be fetched. After all the method invocation, manually close the container through registerShutdownHook().