文章摘要: 摘要内容。
spring容器
org.springframework.context.annotation.AnnotationConfigApplicationContext
- 通过注解的方式配置spring容器
org.springframework.context.support.ClassPathXmlApplicationContext
- 通过xml文件来配置spring容器
步骤
- 创建spring容器
- 配置spring容器
- 启动spring容器
案例
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import tech.magictable.service.config.SpringConfig;
public class Application {
public static void main(String[] ages) {
// 创建spring容器,Java配置类
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
// 将用作配置类的类名注册到spring容器中,即spring容器将到该配置类中读取相关注解
applicationContext.register(SpringConfig.class);
// 启动spring容器
applicationContext.refresh();
}
}
编写配置类
@ComponentScan(“<包路径>”)
- 扫描包路径。
org.springframework.context.annotation.ComponentScan
标识类为Bean对象
在一个类上一行上编写@Component注解,将由配置文件中的扫描包路径读取并注册到spring容器中。
获取Bean对象
applicationContext.getBean(<类名>.class):从spring容器中获取对象。