IOC操作Bean管理注解方式(完全注解开发)
(1)创建配置类,替代xml配置文件
需要让Spring 把一个普通的类认为是配置类
结构图:
SpringConfig类代码如下:
package com.lbj.spring5.comfig;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;@Configuration //作为配置类,替代xml文件
@ComponentScan(basePackages = {"com.lbj"}) //以数组形式写入基本扫描的包
public class SpringConfig {}
测试文件:
package com.lbj.spring5.testdemo;import com.lbj.spring5.comfig.SpringConfig;
import com.lbj.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestSpring5Demo1 {@Testpublic void testService02(){
// 换配置类ApplicationContext context=new AnnotationConfigApplicationContext(SpringConfig.class);UserService userService = context.getBean("userService", UserService.class);System.out.println(userService);userService.add();}}
测试结果:
应用:SpringBoot中做开发