Spring Boot 推荐使用注解的方式向容器中注入组件, 操作如下:
使用 @Configuration 配置类,来表示对应Spring配置文件
使用 @Bean 向容器中注入组件对象
**
* @Configuration 它是spring里的注解,用于标识当前类是一个配置类,来表示对应spirng配置文件
*/
@Configuration
public class EmpConfig {
/**
* @Bean 标识的方法用于向容器中注入组件
* 1. 返回值就是注入容器中的组件对象
* 2. 方法名就是这个组件的 id 值
* @return
*/
@Bean
public EmpService empService2() {
System.out.println(" EmpService 组件注入成功");
return new EmpService();
}
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {
@Autowired
Emp emp;
@Autowired
ApplicationContext context;
@Test
public void testXml() {
EmpService empService2 = (EmpService)context.getBean("empService2");
System.out.println("empService2: " + empService2);
}
}