Spring中怎样实现自动扫描

 时间:2026-02-13 02:14:02

1、首先 ,在Spring中单独给一个类装配,[html] view plain copy

<bean id="customerDAO" class="com.yiibai.customer.dao.CustomerDAO" />  。

Spring中怎样实现自动扫描

2、然后,只需要在xml中配置bean即可,但是如果我们有一大推类要配置,那么一个一个配置就太麻烦了,这个时候用Spring中的自动扫描组件就很方便了。

Spring中怎样实现自动扫描

3、然后,共有4种类型的自动扫描:@Component(任意组件)、@Repository(DAO层组件)、@Service(业务层组件)和@Controller(控制层组件)。

Spring中怎样实现自动扫描

4、然后,将Spring的配置文件改为:<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context-4.2.xsd">    <context:component-scan base-package="cn.itcast" /></beans>。

Spring中怎样实现自动扫描

5、然后,然后使用@Service注解标注PersonServiceBean类,如下:@Servicepublic class PersonServiceBean implements PersonService {    private PersonDao personDao;    public void setPersonDao(PersonDao personDao) {        this.personDao = personDao;    }    @Override    public void save() {        personDao.add();    }}。

Spring中怎样实现自动扫描

6、最后,修改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();    }}。

Spring中怎样实现自动扫描

  • 澳洲父母付费移民获批后需要在澳大利亚居住多久
  • 天月二德贵人应用
  • 重点用能单位能耗在线监测系统
  • 家用抽湿机的三种使用方法
  • 欧洲驾驶法规与习惯(自驾游必看)
  • 热门搜索
    仿写句子大全 fps怎么提高 邮箱地址大全 怎么才能写好字 世界未解之谜大全 邪恶漫画色系大全 综之金手指大全 婚礼请帖怎么写 面食的做法大全家常 鲜海参怎么保存