首先 ,在Spring中单独给一个类装配,[html] view plain copy
然后,只需要在xml中配置bean即可,但是如果我们有一大推类要配置,那么一个一个配置就太麻烦了,这个时候用Spring中的自动扫描组件就很方便了。
然后,共有4种类型的自动扫描:@Component(任意组件)、@Repository(DAO层组件)、@Service(业务层组件)和@Controller(控制层组件)。
然后,将Spring的配置文件改为:
然后,然后使用@Service注解标注PersonServiceBean类,如下:@Servicepublic class PersonServiceBean implements PersonService { private PersonDao personDao; public void setPersonDao(PersonDao personDao) { this.personDao = personDao; } @Override public void save() { personDao.add(); } }。
最后,修改SpringTest类的代码为:public class SpringTest { @Test public void instanceSpring() { AbstractApplicationContext ctx = new ClassPathXmlApplicationContext('beans.xml'); PersonService personService = (PersonService) ctx.getBean('personServiceBean'); PersonDao personDao = (PersonDao) ctx.getBean('personDaoBean'); System.out.println(personService); System.out.println(personDao); ctx.close(); } }。
上述方法为小编整理所得,希望能够帮助到大家。