在第一章 基于 注解 的方式 初始化 spring 容器 中我们讲了如何基于注解的方式来初始化 spring 容器
我们通过为类添加@Component注解的方式 来将类交给spring管理 像这样
@Component //该注解 spring 自动为类创建实例对象
public class MessageService {
......
}
前面我们讲的都是 在函数入口 main 上添加 @ComponentScan 自动扫描组件 来进行测试的
@ComponentScan
public class Application {
public static void main(String[] args) {
......
}
}
而在实际开发的过程当中 如果我们不使用 入口方法 来调用应用程序
也就是说我们的应用程序有可能是通过其他手段来调用的 比如通过微信端 , 安卓端
- 如果我们不存在主类的话 就没有办法添加 @ComponentScan 组件扫描 这个时候我们就需要对 main 和 扫描组件 进行解耦
我们单独创建一个 配置类 来专门 进行自动组件扫描
@Configuration //声明该类是一个配置类
@ComponentScan
public class AppConfig {
}
最后将 AnnotationConfigApplicationContext 中的 Application.class 改为我们的配置类
public class Application {
public static void main(String[] args) {
//ApplicationContext context = new AnnotationConfigApplicationContext( Application.class );
ApplicationContext context = new AnnotationConfigApplicationContext( AppConfig.class );
}
}