Spring基于注解的IOC入门

8 篇文章 0 订阅

模拟表现层,业务层,持久层的类

基于注解的IOC配置

Maven工程 pom.xml导入spring依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>spring_eesy_FirstIOC</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.17.RELEASE</version>
        </dependency>
    </dependencies>
</project>

配置bean…xml文件

  1. 创建一个类路径下的xml
    在这里插入图片描述

  2. 去Spring Framework Documentation官网CTRL+f 查找xmlns:context
    3在这里插入图片描述

  3. 将右侧红色框的内容复制到bean.xml

<?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"
       xmlns:comtext="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
        https://www.springframework.org/schema/context/spring-context.xsd">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在bean的约束中,
而是一个名称为context名称空间和约束-->
    <comtext:component-scan base-package="com.itheima"></comtext:component-scan>
</beans>

在com.itheima包下的任意类 使用注解@Component

public class Client {
    /*

    * 获取Spring的IOC核心容器,并根据id来获取对象*/
    public static void main(String[] args){
        //1.获取核心容器对象
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        IAccountService as = (IAccountService) applicationContext.getBean("accountServiceImpl");
        //IAccountDao adao= applicationContext.getBean("accountDao",IAccountDao.class);
        System.out.println(as);
        }
}
@Component
public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public AccountServiceImpl(){
        System.out.println("对象创建了");
    }
    public void saveAccount(){

        accountDao.saveAccount();
    }
}

运行结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值