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,否则需要进行设置,才能读取得到。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论