当前位置: 代码迷 >> 综合 >> java类中获得spring中的bean
  详细解决方案

java类中获得spring中的bean

热度:86   发布时间:2024-01-15 09:27:09.0

1.工具类:获得ApplicationContext对象

public class SpringTest {public ApplicationContext getContext(){String conf = "applicationContext.xml";ApplicationContext ac = new ClassPathXmlApplicationContext(conf);return ac;}}

2.例子:做dao层的测试类,获取dao对象

public class TestBookDao extends SpringTest{@Testpublic void test1(){BookDao bookDao = getContext().getBean("bookDao",BookDao.class);//获得beanList<NoteBook> list = bookDao.findByUserId("48595f52-b22c-4485-9244-f4004255b972");for(NoteBook book : list){System.out.println(book.getCn_notebook_name());}}}