1.创建一个config包,包下创建empclass
package com.cc.springboot01init.config;
import com.cc.springboot01init.service.EmpService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//spring里面的注解,用于标识当前类是一个配置类,来表示对应spring配置文件
@Configuration
public class EmpConfig {
//返回值就是注入容器中的组件对象
//方法名是组件的id
//@Bean标识的方法用于向容器中注入组件
@Bean
public EmpService empService(){
System.out.println("EmpService组件注入成功");
return new EmpService();
}
}
2.将应用程序中的 //@ImportResource(locations = {"classpath:spring01.xml"}) 注释
3.测试应用中使用
package com.cc.springboot01init;
import com.cc.springboot01init.bean.Emp;
import com.cc.springboot01init.service.EmpService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import javax.xml.bind.SchemaOutputResolver;
@SpringBootTest
class SpringBoot01InitApplicationTests {
// 注入
@Autowired
ApplicationContext context;
@Test
void testXml() {
// EmpService empService= (EmpService)context.getBean("empService");
// System.out.println(empService);
EmpService empService= (EmpService)context.getBean("empService");
System.out.println(empService);
}
}