Spring实现Aware接口自定义获取bean的两种方式
程序员文章站
2024-02-29 10:28:52
在使用编程时,常常会遇到想根据bean的名称来获取相应的bean对象,这时候,就可以通过实现beanfactoryaware来满足需求,代码很简单:
@servi...
在使用编程时,常常会遇到想根据bean的名称来获取相应的bean对象,这时候,就可以通过实现beanfactoryaware来满足需求,代码很简单:
@servicepublic class beanfactoryhelper implements beanfactoryaware { private static beanfactory beanfactory; @override public void setbeanfactory(beanfactory beanfactory) throws beansexception { this.beanfactory = beanfactory; } public static object getbean(string beanname){ if(beanfactory == null){ throw new nullpointerexception("beanfactory is null!"); } return beanfactory.getbean(beanname); } }
还有一种方式是实现applicationcontextaware接口,代码也很简单:
@service public class applicationcontexthelper implements applicationcontextaware { private static applicationcontext applicationcontext; @override public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { this.applicationcontext = applicationcontext; } public static object getbean(string beanname){ if(applicationcontext == null){ throw new nullpointerexception("applicationcontext is null!"); } return applicationcontext.getbean(beanname); } }
上面两种方法,只有容器启动的时候,才会把 beanfactory 和 applicationcontext 注入到自定义的helper类中,如果在本地junit测试的时候,如果需要根据bean的名称获取bean对象,则可以通过classpathxmlapplicationcontext来获取一个applicationcontext,代码如下:
@test public void test() throws sqlexception { //通过从classpath中加载spring-mybatis.xml实现bean的获取 applicationcontext context = new classpathxmlapplicationcontext("spring-mybatis.xml"); iuserservice userservice = (iuserservice) context.getbean("userservice"); user user = new user(); user.setname("test"); user.setage(20); userservice.adduser(user); }
总结
以上就是小编分享给大家的java编程实现aware接口自定义获取bean的两种方式的全部内容,希望对大家有所帮助。如果有什么问题,可以留言,小编会及时回复大家。感谢大家对本站的支持!