10、Spring IOC扫描器

Spring IOC扫描器:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
实例:
spring配置文件:定义一个扫描器,并设置扫描器的扫描范围为com.xxxx包下

<?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
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--自动化扫描器:设置自动化扫描的范围
        作用:bean对象的统一管理,简化开发配置,提高开发效率
        1、设置自动化扫描的范围(如果bean对象不在扫描范围内,即使声明了注解,也不会被实例化)
        2、在需要被实例化的javaBean的类上添加指定的注解(注解声明在类级别),**bean对象的id属性默认的是类名的首字母小写
        3、Dao层:@Repository,Service层:@Service,Controller层:@Controller,任意类:@Component
        注意:开发过程中建议按照规则声明注解
    -->
    <context:component-scan base-package="com.xxxx"/>
</beans>

TypeController类:类中需要注入TypeService对象

@Controller
public class TypeController {
    @Autowired
    private TypeService typeService;
    public void test(){
        System.out.println("TypeController Test...");
        typeService.test();
    }
}

TypeService类:类中需要注入TypeDao对象

@Service
public class TypeService {
    @Resource
    private TypeDao typeDao;
    public void test(){
        System.out.println("TypeService Test...");
        typeDao.test();
    }
}

TypeDao类:

@Repository
public class TypeDao {
    public void test(){
        System.out.println("TypeDao Test...");
    }
}

测试类:

public class App02
{
    public static void main( String[] args )
    {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring02.xml");
        TypeDao typeDao = (TypeDao) ac.getBean("typeDao");
        typeDao.test();
    }
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值