关于ApplicationContext的三个常用实现类,
分享于 点击 31229 次 点评:284
关于ApplicationContext的三个常用实现类,
目录
- ApplicationContext的三个常用实现类
- applicationContext=null的问题
- 问题
- 处理1:检查目录
- 处理2:设置@ComponentScan
- 总结
ApplicationContext的三个常用实现类
FileSystemXmlApplicationContext
:可以加载磁盘路径下的配置文件(不常用)
public class Client { public static void main(String[] args) { ApplicationContext context = new FileSystemXmlApplicationContext("C:\\Users\\ghh\\Desktop\\bean.xml"); AccountService service = context.getBean("accountService", AccountService.class); AccountDao accountDao = context.getBean("accountDao", AccountDao.class); System.out.println(service); System.out.println(accountDao); } }
ClassPathXmlApplicationContext
:可以加载类路径下的配置文件
要求配置文件必须在类路径下面
public class Client { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); AccountService service = context.getBean("accountService", AccountService.class); AccountDao accountDao = context.getBean("accountDao", AccountDao.class); System.out.println(service); System.out.println(accountDao); } }
AnnotationConfigApplicationContext
:读取注解创建容器
applicationContext=null的问题
问题
要对一个公共模块项目,进行一个拆分,做一个细化。
调整的时候,调整了启单类的位置(并未注意到),单元测试的时候,就报错。
import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringUtils.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) { return applicationContext.getBean(name); } public static <T> T getBean(Class<T> requiredType) { return applicationContext.getBean(requiredType); } }
setApplicationContext 调试的时候,方法没进去。说明bean没有初始化。
处理1:检查目录
启动类要在顶层的位置,这样才会读整个,就不用设置@ComponentScan
处理2:设置@ComponentScan
指定具体读取的路径
@ComponentScan(basePackages = {"com.basic.common"}) public class BasicCommonApplication { public static void main(String[] args) { SpringApplication.run(BasicCommonApplication.class, args); } @Bean public DozerBeanMapperFactoryBean dozerBeanMapperFactoryBean() { return new DozerBeanMapperFactoryBean(); } }
心得:
如果在单个项目中,启动类需要在顶层的位置,才不用设置@ComponentScan,否则需要进行设置,才能读取得到。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。
您可能感兴趣的文章:- SpringBoot中@Autowired爆红原理分析及解决
- 解决@ServerEndpoint不能注入@Autowired的问题
- Spring中ApplicationContext的拓展功能详解
- Spring中的ApplicationContext与BeanFactory详解
- 使用@Autowired可以注入ApplicationContext
用户点评