使用SpringtUtil获取SpringIoC容器中的Bean
方便获取Spring IoC容器中的Bean,调用方法:getBean(String name)
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class SpringtUtil {
private static SpringtUtil instance = new SpringtUtil();
private static ApplicationContext context;
public static final String spring_context_configfile = "spring.context.configfile";
public static Object getBean(String name) {
return getContext().getBean(name);
}
public static ApplicationContext getContext() {
return SpringtUtil.getInstance().context;
}
public static SpringtUtil getInstance()
{
return instance;
}
private SpringtUtil()
{
try
{
String springContextFileName =PropertiesUtil.getProperty(spring_context_configfile);
//System.out.println(springContextFileName);
context = new FileSystemXmlApplicationContext(springContextFileName);
} catch (Throwable t) {
t.printStackTrace();
}
}
public static void main(String args)
{
try {
UserService userService= (UserService)SpringtUtil.getBean("userService");
userService.test("id", "name");
} catch (Exception e) {
e.printStackTrace();
}
编辑推荐:
温馨提示:因考试政策、内容不断变化与调整,长理培训网站提供的以上信息仅供参考,如有异议,请考生以权威部门公布的内容为准! (责任编辑:长理培训)
点击加载更多评论>>