package com.paas.app.hello;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
// @Configuration // 这种模式下该注解已经没有必要使用
@ComponentScan(value = "com.paas.app.hello") // 这种模式下该注解有效,指明了组件扫描范围
public class Spring {
public static AnnotationConfigApplicationContext initApplicationContext() {
// 注意 :
//// 1. 这里 类AnnotationConfigApplicationContext 类加载器跟下面的 componentsClassLoader 可能不同,要留意这一点 。
//// 2. 对象 applicationContext 新建时,所使用的用来加载组件bean对象的类加载器,也就是其属性 getClassLoader()
//// 默认是 类 AnnotationConfigApplicationContext 的类加载器 。
//// 3. 如果 applicationContext.getClassLoader() 和目标组件bean对象的类加载器不一致,会导致找不到目标组件bean,
//// 所以一定要将 applicationContext 对象的 classLoader 属性设置成目标组件bean对象的类加载器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
// 类加载器的设置很重要,如果目标组件类所在包下的类已经被加载,这里一定要设置使用同样的类加载器
//// 前提假设 : 类 Spring 是目标bean组件所在的包,并且目标bean组件类,包括 Spring 在内都已经被同一类加载器加载,
//// 这里获取目标bean组件的类加载器并设置到 applicationContext 对象的 classLoader 属性上,这样
//// applicationContext 就能正常地发现目标组件了
ClassLoader componentsClassLoader = Spring.class.getClassLoader();
// 该模式下必须要保证这里指定的ClassLoader和Spring类的类加载器一致
applicationContext.setClassLoader(componentsClassLoader);
// 此时注册组件类 Spring.class 到 applicationContext 时,发现组件bean所使用的类加载器会是 componentsClassLoader
applicationContext.register(Spring.class);
applicationContext.refresh(); // 该方法需要配合 register 方法使用
return applicationContext;
}
}
- 应用方法
- 复制该类到你的项目中特定的java包下面,假设是
com.paas.app.hello; - 在
com.paas.app.hello包下面现在就可以使用Spring注解@Configuration/@Bean,@Component,@Service,@Autowired定义和引入bean组件了。
- 复制该类到你的项目中特定的java包下面,假设是
Bean获取方法
// 初始化 ApplicationContext , 这个过程中会扫描包 com.paas.app.hello 下通过注解方式定义的所有bean
// 组件登记到 applicationContext 中
ApplicationContext applicationContext = Spring.initApplicationContext();
// 假设存在一个类型为 TestService 的bean组件,这样获取相应 bean 组件然后就可以使用了
TestService testService = applicationContext.getBean(TestService.class);
testService.sayHello(); // 使用获取的 TestService bean 组件 testService

本文详细介绍了如何在Spring框架中使用注解@ComponentScan进行组件扫描,以及在特定场景下设置类加载器以确保正确加载目标组件。通过Spring类的initApplicationContext方法初始化ApplicationContext,确保扫描com.paas.app.hello包下的所有注解定义的bean,并能正确获取和使用这些bean。
1万+

被折叠的 条评论
为什么被折叠?



